Bullet Shooting problem (bullet stops moving after shooting another)
So I am working on Asteroids clone project. My problem in this project is shooting. So when I shoot the bullet it goes in right direction based on angle of the player but when I shoot another bullet previous one stops moving.
Here is the bullet class :
class Bullet:
def __init__(self, rocket):
self.bullets = []
self.angle = 0
self.bullet = pygame.Rect(rocket.posX - 30, rocket.posY - 20, 30, 30)
def shoot(self, rocket):
self.angle = rocket.angle
self.bullet = pygame.Rect(rocket.posX - 30, rocket.posY - 20, 30, 30)
self.bullets.append(self.bullet)
def update(self):
self.angle = self.angle % 360
self.xDir = math.radians(self.angle)
self.yDir = math.radians(self.angle)
self.bullet.x += math.cos(self.xDir) * 2.0
self.bullet.y -= math.sin(self.yDir) * 2.0
def drawToScreen(self,screen):
for self.bullet in self.bullets:
pygame.draw.rect(screen, (0, 255, 0), self.bullet)
and here is the game loop (ignore some comments):
while run:
#angle = angle % 360
dt = clock.tick(FPS)/1000
#xDir = math.radians(angle)
#yDir = math.radians(angle)
#randRect.x += math.cos(xDir) * 2.0
#randRect.y -= math.sin(yDir) * 2.0
rocket.update()
bullet.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet.shoot(rocket)
keys_pressed = pygame.key.get_pressed()
rocket.movement(keys_pressed, dt)
drawToWindow(screen, rocket, bullet)
#pygame.draw.rect(screen, (0, 0, 255), randRect)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
It looks like you're not actually moving each bullet in self.update(), just the most recent bullet that was created in self.shoot(). Try something like:
def update(self):
self.angle = self.angle % 360
self.xDir = math.radians(self.angle)
self.yDir = math.radians(self.angle)
for bullet in self.bullets:
bullet.x += math.cos(self.xDir) * 2.0
bullet.y -= math.sin(self.yDir) * 2.0
Also, I noticed you're doing "for self.bullet in self.bullets" in the self.drawToScreen() method, and that seems like that might cause issues (if it isn't already). Try doing just:
for bullet in self.bullets:
pygame.draw.rect(screen, (0, 255, 0), bullet)