我目前正在研究一个自上而下的射击游戏,其中玩家处于固定位置,敌人来自随机坐标。但是,敌人与玩家碰撞时的碰撞没有作用。我想知道是否有人可以提供帮助。 (我不太擅长编码)。感谢您的任何帮助。
代码:
播放器类:
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = character
self.rect = self.image.get_rect()
def drawPlayer(self, image, angle, position):
player=pygame.transform.rotate(image, angle)
pRect=player.get_rect(center=position)
screen.blit(player, pRect)
敌对阶级:
class Mob(pygame.sprite.Sprite):
def __init__(self, start_x, start_y, dest_x, dest_y):
pygame.sprite.Sprite.__init__(self)
self.image = badguy
self.rect = self.image.get_rect()
self.rect.x = start_x
self.rect.y = start_y
self.floating_point_x = start_x
self.floating_point_y = start_y
x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff, x_diff);
velocity = random.randrange(1,3)
self.change_x = math.cos(angle) * velocity
self.change_y = math.sin(angle) * velocity
pygame.display.flip()
def update(self):
self.floating_point_y += self.change_y
self.floating_point_x += self.change_x
self.rect.y = int(self.floating_point_y)
self.rect.x = int(self.floating_point_x)
碰撞部分:
all_sprites_list.update()
hits = pygame.sprite.spritecollide(player, mobs, True)
if hits:
running = False
答案 0 :(得分:3)
pygame.sprite.groupcollide()
使用pygame.sprite.Sprite
对象的.rect
属性进行碰撞测试。因此,您必须更新self.rect
属性,而不是使用局部变量pRect
:
class Player(pygame.sprite.Sprite):
# [...]
def drawPlayer(self, image, angle, position):
player = pygame.transform.rotate(image, angle)
self.rect = player.get_rect(center = position)
screen.blit(player, self.rect)