2

I am creating a type Space Invader game, with a ship which can fire a bullet from its position, with direction velocity.

When I create a bullet from key input, the update method in Bullet affects the Players position and velocity as well, almost as it reference to the same values as Player. I want the bullet to fire from the players position and velocity.

class Player(pygame.sprite.Sprite):
def __init__(self, bullet_list):
super().__init__()
self.pos = Vector2(100,100)
self.vel = Vector2(1,1)
self.bullet_list = bullet_list

def input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.bullet_list.add(Bullet(self.pos, self.vel))

def update():
self.input()

class Bullet(pygame.sprite.Sprite):
def __init__(self, pos, vel):
super().__init__()
self.pos = pos
self.vel = vel

def update():
self.pos += vel

while True:
bullets = pygame.sprite.group()
players = pygame.sprite.group(Player1(bullets))

bullets.update()
players.update()

Tried to add the bullet in the main loop, but with same results.

marloop007
  • 21
  • 4

2 Answers2

3
self.bullet_list.add(Bullet(self.pos, self.vel))

With this line you initialize the Bullet, using the position and velocity vector of the player. You are handing them over to the Bullet object per reference, which means they are in fact the same. The reference to the vectors which the Bullet receives points at the same vectors the Player has. You either want to make a copy of the vectors when you initialize the Bullet or change the constructor of the Bullet class to accept the integer or float values you use instead of the vectors.

dhu
  • 31
  • 1
2

You need to copy the position and velocity instead of passing references to the vector objects to the Bullet class. Construct new Vector2 objects from the source objects:

self.bullet_list.add(Bullet(self.pos, self.vel))

self.bullet_list.add(Bullet(Vector2(self.pos), Vector2(self.vel)))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174