I am creating a game where you shoot enemies in a top-down format. My bullet and enemy function properly in every aspect except where it has to delete itself. I have hooked it up to where if the bullet collides with the enemy or 5 seconds have passed, the bullet would delete itself. It does do that, except the code continually iterates to create a sprite and kill it as the bullet moves for some reason, and still shows the bullet on the screen as if nothing is happening to it. Can someone tell me why the code is iterating the creation of a bullet and the deletion of it so many times?
-------- CODE --------
method in player class
def shoot(self):
pos = pygame.mouse.get_pos()
pos += camera_group.offset
click = pygame.mouse.get_pressed()
if click[0] and not self.shooting:
self.shooting = True
# create bullet instance if player shoots
bullet = Bullet(self.rect.centerx, self.rect.centery, "bullet", pos, camera_group)
bullet_group.add(bullet)
if not click[0]:
self.shooting = False
bullet class
class Bullet(Entity):
def __init__(self, x, y, image, pos, group):
super().__init__(x, y, image, group)
pygame.sprite.Sprite.__init__(self)
# creating and scaling image
self.image = pygame.transform.flip(self.image, True, False)
self.image = pygame.transform.scale(self.image, (32, 16))
# creating rect
self.x = x
self.y = y
self.speed = 8
self.mousepos = pos
# calculating angle of bullet
self.angle = math.atan2(pos[1] - y, pos[0] - x)
self.angle_deg = (self.angle * (180 / math.pi))
self.image = pygame.transform.rotate(self.image, self.angle_deg * -1)
# calculating vel_x/vel_y
dx = self.mousepos[0] - player.rect.centerx
dy = self.mousepos[1] - player.rect.centery
total = abs(dx) + abs(dy)
self.vel_x = (self.speed * (dx / total))
self.vel_y = (self.speed * (dy / total))
# setting variable to store time of bullet creation
self.start_time = pygame.time.get_ticks()
def update(self):
if pygame.time.get_ticks() - self.start_time > 50 and len(bullet_group) >= 1:
bullet_group.sprites()[0].kill()
elif self.rect.colliderect(enemy):
bullet_group.sprites()[0].kill()
enemy.kill()
else:
# movement
self.x += self.vel_x
self.y += self.vel_y
self.rect.x = int(self.x)
self.rect.y = int(self.y)
Don't kill the first bullet in the Group , just delete the bullet object itself:
bullet_group.sprites()[0].kill()
self.kill()
method update
in class Bullet
:
class Bullet(Entity):
# [...]
def update(self):
if pygame.time.get_ticks() - self.start_time > 50 and len(bullet_group) >= 1:
self.kill()
elif self.rect.colliderect(enemy):
self.kill()
enemy.kill()
else:
# movement
self.x += self.vel_x
self.y += self.vel_y
self.rect.x = int(self.x)
self.rect.y = int(self.y)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.