虽然当我使用pygame.sprite.collide_rect
or时检测到碰撞pygame.sprite.collide_circle
,但当我尝试为精灵分配位掩码并运行它时,没有检测到碰撞。(这wall.collision_action()
使得第一个圆圈以与另一个圆圈相同的速度和方向移动)虽然这现在不是问题,
因为我正在使用圆圈的图像,这使得 pygame.sprite.collide_circle 工作正常,将来当我将使用更详细和非圆形的精灵。
代码:
import pygame, sys, math
from pygame.locals import *
pygame.init()
class ball_class(pygame.sprite.Sprite):
def __init__(self, surface):
self.surface = surface
self.x = 250
self.y = 250
self.vy = 0
self.vx = 0
self.sprite = pygame.sprite.Sprite()
self.sprite.image = pygame.image.load("ball.png").convert()
self.sprite.rect = self.sprite.image.get_rect(center = (self.x, self.y))
self.sprite.rect.topleft = [int(self.x), int(self.y)]
self.sprite.mask = pygame.mask.from_surface(self.sprite.image)
def event(self, event):
if event.key == K_UP:
self.vy = -1
self.vx = 0
elif event.key == K_DOWN:
self.vy = 1
self.vx = 0
elif event.key == K_LEFT:
self.vx = -1
self.vy = 0
elif event.key == K_RIGHT:
self.vx = 1
self.vy = 0
def move(self):
self.y += self.vy
self.x += self.vx
self.sprite.rect.topleft = [int(self.x), int(self.y)]
self.sprite.mask = pygame.mask.from_surface(self.sprite.image)
def draw(self, surface):
surface.blit(self.sprite.image, self.sprite.rect)
def position(self):
return self.sprite.rect()
class wall_class(pygame.sprite.Sprite):
def __init__(self, surface):
self.surface = surface
self.x = 250
self.y = 100
self.vy = 0
self.sprite = pygame.sprite.Sprite()
self.sprite.image = pygame.image.load("ball.png").convert()
self.sprite.rect = self.sprite.image.get_rect(center = (self.x, self.y))
self.sprite.rect.topleft = [int(self.x), int(self.y)]
self.sprite.mask = pygame.mask.from_surface(self.sprite.image)
def draw(self, surface):
surface.blit(self.sprite.image, self.sprite.rect)
def collision_action(self):
self.vy = ball.vy
self.vx = ball.vx
self.x += self.vx
self.y += self.vy
self.sprite.rect.topleft = [int(self.x), int(self.y)]
def gameQuit():
pygame.quit()
sys.exit()
screen = pygame.display.set_mode((500, 500), 0, 32)
ball = ball_class(screen)
wall = wall_class(screen)
clock = pygame.time.Clock()
while True:
screen.fill((0, 0, 0))
ball.move()
ball.draw(screen)
wall.draw(screen)
is_a_collision = pygame.sprite.collide_mask(wall.sprite, ball.sprite)
if is_a_collision:
wall.collision_action()
for event in pygame.event.get():
if event.type == QUIT:
gameQuit()
elif event.type == KEYDOWN:
ball.event(event)
clock.tick(100)
pygame.display.update()