我不久前问过这个问题,但答案并不完全有帮助,而且我不相信我发布了最小的可重现示例。一段时间(self.lifetime)过去后,我试图杀死我的子弹。 self.kill() 命令被执行,但它并没有从相机组中删除子弹,这就是我用来绘制所有子弹的。
相关代码:
Player.shoot():
def shoot(self, pos):
self.current_time = pg.time.get_ticks()
# Allow the player to shoot (but not continuously)
if not self.shooting and self.current_time - self.last_shot_time >= self.shoot_cooldown:
self.last_shot_time = self.current_time
# Setting self.shooting to True so that only one bullet is created
self.shooting = True
# Creating the bullet
bullet = Bullet(self.rect.centerx, self.rect.centery, "bullet", pos, 2, a_s.camera)
# Reset self.shooting
self.shooting = False
Bullet.update():
def update(self):
# Killing the bullet after self.lifetime has passed
if pg.time.get_ticks() - self.start_time > self.lifetime:
self.kill()
print("Killing")
# Moving the bullet (accurately, self.x is float while self.rect.x can only be int)
self.x += self.vel_x
self.y += self.vel_y
self.rect.x = int(self.x)
self.rect.y = int(self.y)
实体类:(bullet继承于此)
class Entity(pg.sprite.Sprite):
def __init__(self, speed, group):
pg.sprite.Sprite.__init__(self)
self.speed = speed
group.add(self)
我还添加了一个 Pastebin 来允许您重现此示例,但是您需要目录中的 3 个标题为“ground.png”、“player.png”和“bullet.png”的图像才能运行它。
巴斯德宾:https://pastebin.com/Vi57HF1i
我使用的图片(归功于其他人,不确定我从哪里得到它们):https://i.stack.imgur.com/09ocm.jpg