我想在我的乒乓球游戏中实施子弹,我的桨可以射出子弹。现在,我只想专注于PlayerPaddle射出向右移动的子弹。这些子弹将来自桨叶的位置。但是,我不知道如何处理这个问题。我相信制作一个精灵组会使我的项目过于复杂,我只是希望我的子弹能够碰到我最终的乒乓球。这就是我到目前为止所拥有的。
class PlayerPaddle(Image):
def __init__(self, screen_size, width, height, filename, color=(255,0,0)):
# speed and direction have to be before super()
self.speed = 3
self.direction = 0
super().__init__(screen_size, width, height, filename, color=(255, 0, 0))
self.rect.centerx = 40
self.rect.centery = screen_size[1] // 2
self.rect.height = 100
def update(self):
self.rect.centery += self.direction*self.speed # <--- use directly rect.centery
super().update()
#self.rect.center = (self.centerx, self.centery) # <-- don't need it
if self.rect.top < 0:
self.rect.top = 0
if self.rect.bottom > self.screen_size[1]-1:
self.rect.bottom = self.screen_size[1]-1
def handle_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.direction = -1
elif event.key == pygame.K_DOWN:
self.direction = 1
elif event.key == pygame.K_LEFT:
self.turnLeft()
elif event.key == pygame.K_RIGHT:
self.turnRight()
elif event.key == pygame.K_u:
bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
bullet.rect.centerx = self.rect.centerx
bullet.rect.centery = self.rect.centery
bullet.draw()
bullet.update()
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP and self.direction == -1:
self.direction = 0
elif event.key == pygame.K_DOWN and self.direction == 1:
self.direction = 0
这是我的子弹课
class Bullet(Image):
def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):
super().__init__(screen_size, width, height, filename, color = (255, 0, 0))
def update(self):
self.rect.centery -= 3
答案 0 :(得分:1)
我会在Group()
PlayerPaddle()
self.bullets_group = pygame.sprite.Group()
并将其用作PlayerPaddle()
self.player_paddle = PlayerPaddle(..., self.bullets_group)
这样玩家可以轻松地将子弹添加到组
elif event.key == pygame.K_u:
bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
bullet.rect.centerx = self.rect.centerx
bullet.rect.centery = self.rect.centery
self.bullets_group.add(bullet)
和mainloop
可以绘制和更新
def Update():
self.bullets_group.update()
self.player_paddle.update()
self.ai_paddle.update(..., self.bullets_group)
def Render():
self.bullets_group.draw()
self.player_paddle.draw()