Reputation: 196
I'm trying to make a bullet move in Pygame. Apologies if it has a simple fix, I just can't think at the moment.
This is what I run when I detect that the "1" button is pressed.
if pygame.event.get().type == KEYDOWN and e.key == K_1:
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
entities.add(bullet)
bullet_list.add(bullet)
bullet.update()
...and this is the actual bullet class. The spacing is a bit off.
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super(Bullet, self).__init__()
self.image = pygame.Surface([4, 10])
self.image.fill(pygame.Color(255, 255, 255))
self.isMoving = False
self.rect = self.image.get_rect()
def update(self):
for i in range(20):
self.rect.x += 3
I understand that the update method is happening instantly rather than the slower movement I want. How am I supposed to make the bullet move slower? All the answers that I've seen involve completely stopping the program instead of just stopping the one object. Is there a way around it?
Upvotes: 0
Views: 89
Reputation: 1224
You need to update all bullets on every game tick, not just when a player presses a button.
So, you'll want something like this as your event loop:
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
if event == KEYDOWN and event.key == K_1:
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
entities.add(bullet)
bullet_list.add(bullet)
for bullet in bullet_list:
bullet.update()
And, modify the Bullet class to do incremental moves, like so:
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super(Bullet, self).__init__()
self.image = pygame.Surface([4, 10])
self.image.fill(pygame.Color(255, 255, 255))
self.isMoving = False
self.rect = self.image.get_rect()
def update(self):
self.rect.x += 3
Upvotes: 1