I'm currently developing a game for some school work using the PyGame library for Python. I'm almost done with most of the game's core mechanics, but have gotten hung up on the shooting mechanics. My current code is too long to post fully, but I'll put excerpts of it and explain what I have so far.
all_sprites_list = pygame.sprite.Group()
bullets = []
bullet_list = pygame.sprite.Group()
bullet_speed = 10
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([4,10])
self.image.fill(red)
self.rect = self.image.get_rect()
def update(self):
if self.rect.x > chx:
self.rect.x -= bullet_speed
elif self.rect.x < chx:
self.rect.x += bullet_speed
if self.rect.y > chy:
self.rect.y -= bullet_speed
elif self.rect.y < chy:
self.rect.y += bullet_speed
This code shows the class I have for my bullets and their movement. The problems with this right now are that A) the bullets get stuck around the crosshair position, of which the chx
and chy
variables show the x and y position of the mouse.
if event.type == pygame.MOUSEBUTTONDOWN:
bullet = Bullet()
if weapon == "hg" and hg_move == True:
bullet.rect.x = hgrect.x
bullet.rect.y = hgrect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
This code shows an example of one of the firing commands later in the main game loop. hg
, hg_move
, and hgrect.x/y
are all variables used for the movement of the character depending on the type of weapon he is holding.
Some of the main issues are seemingly caused by the fact that I can't find a way store a static value of the likes of the crosshair positions, or to keep the bullets going on a trajectory until they leave the screen or hit an object.
Any help would be greatly appreciated!