Here's a complete solution. The player has a direction
attribute which I change to 'left'
or 'right'
when the player presses one of the corresponding keys. When a bullet is created, I pass the player.direction
to the bullet instance and then set its image and velocity depending on the direction.
In order to move the sprites, I add the velocity to the position (which are lists in this example) and finally I update the rect because it's needed for the blitting and collision detection. Actually, I'd use pygame.math.Vector2
s for the pos
and velocity
, but I'm not sure if you are familiar with vectors.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
screen_rect = screen.get_rect()
PLAYER_IMG = pg.Surface((30, 50))
PLAYER_IMG.fill(pg.Color('dodgerblue1'))
BULLET_IMG = pg.Surface((16, 8))
pg.draw.polygon(BULLET_IMG, pg.Color('sienna1'), [(0, 0), (16, 4), (0, 8)])
BULLET_IMG_LEFT = pg.transform.flip(BULLET_IMG, True, False)
class Player(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = PLAYER_IMG
self.rect = self.image.get_rect(center=pos)
self.velocity = [0, 0]
self.pos = [pos[0], pos[1]]
self.direction = 'right'
def update(self):
self.pos[0] += self.velocity[0]
self.pos[1] += self.velocity[1]
self.rect.center = self.pos
class Bullet(pg.sprite.Sprite):
def __init__(self, pos, direction):
super().__init__()
if direction == 'right':
self.image = BULLET_IMG
self.velocity = [9, 0]
else:
self.image = BULLET_IMG_LEFT
self.velocity = [-9, 0]
self.rect = self.image.get_rect(center=pos)
self.pos = [pos[0], pos[1]]
def update(self):
# Add the velocity to the pos to move the sprite.
self.pos[0] += self.velocity[0]
self.pos[1] += self.velocity[1]
self.rect.center = self.pos # Update the rect as well.
# Remove bullets if they're outside of the screen area.
if not screen_rect.contains(self.rect):
self.kill()
def main():
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
bullets = pg.sprite.Group()
player = Player((100, 300))
all_sprites.add(player)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
bullet = Bullet(player.rect.center, player.direction)
bullets.add(bullet)
all_sprites.add(bullet)
elif event.type == pg.KEYDOWN:
if event.key == pg.K_d:
player.velocity[0] = 5
player.direction = 'right'
elif event.key == pg.K_a:
player.velocity[0] = -5
player.direction = 'left'
elif event.type == pg.KEYUP:
if event.key == pg.K_d and player.velocity[0] > 0:
player.velocity[0] = 0
elif event.key == pg.K_a and player.velocity[0] < 0:
player.velocity[0] = 0
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pg.quit()