My plan was to make circles spawn at regular intervals and go towards my mouse at a certain speed. I got the first part of this working. Although, when a new sprite is spawned, the previous one stops moving and so on as if they were not getting updated anymore. I am trying to make them all move simultaneously towards my mouse instead of just the new one.
I am fairly new, so feel free to add any other input on flaws you see.
Here is the part of code relevant to this:
# Enemy
class Enemy (pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.x = 0
self.y = 0
self.speed = 2
self.change_x = 0
self.change_y = 0
self.update()
def update(self):
dx, dy = (pygame.mouse.get_pos()[0]+8) - self.x, (pygame.mouse.get_pos()[1]+8) - self.y
dist = math.hypot(dx, dy)
dx, dy = dx / dist, dy / dist
self.change_x += dx * self.speed
self.change_y += dy * self.speed
def make_enemies():
enemy = Enemy()
enemy.change_x = random.randrange(0, 800)
enemy.change_y = random.randrange(0, 600)
enemy.speed = 2
return enemy
enemy_list = []
spawn = make_enemies()
enemy_list.append(spawn)
add_enemy = pygame.USEREVENT + 1
pygame.time.set_timer(add_enemy, 1000)
# Game loop
done = False
while not done:
# RGB - RED, GREEN, BLUE (0-255)
screen.fill(BACKGROUND)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == add_enemy:
spawn = make_enemies()
enemy_list.append(spawn)
for enemy in enemy_list:
enemy.x = enemy.change_x
enemy.y = enemy.change_y
pygame.draw.circle (screen, WHITE, [enemy.change_x, enemy.change_y], BALL_SIZE)
enemy.update()
clock.tick(100)
pygame.display.update()
>Solution :
You are calling enemy.update() outside of your for loop. So, only the last enemy in the list is updating. Moving it inside your for loop should take care of it.
for enemy in enemy_list:
enemy.x = enemy.change_x
enemy.y = enemy.change_y
pygame.draw.circle (screen, WHITE, [enemy.change_x,
enemy.change_y], BALL_SIZE)
enemy.update()