I have a class called Magic as well as a class called Player. In the player class there is a variable called self.direction which is a pygame.math.Vector2() which I update in my input function. However when I create the Magic class in the input function in the Player class I give it the self.direction variable as the direction, I intended to have the direction be the direction when the Magic class was created and not change. But when I run my code the direction constantly seems to updating itself to my Player class self.direction even when it isn’t supposed to.
Below is the code:
class Magic(pygame.sprite.Sprite):
def __init__(self,pos,groups,dir):
super().__init__(groups)
self.image = pygame.image.load('rock.png').convert_alpha()
self.rect = self.image.get_rect(topleft = pos)
self.direction = dir
print("i have been called")
def move(self):
self.rect.center += self.direction
print(self.rect.center)
#print(self.direction)
def update(self):
self.move()
class Player(pygame.sprite.Sprite):
def __init__(self,pos,groups,obstacles_sprites,visible_sprites):
super().__init__(groups)
global plr
self.image = pygame.image.load('player.png').convert_alpha()
self.rect = self.image.get_rect(topleft = pos)
self.direction = pygame.math.Vector2()
self.obstacle_sprites = obstacles_sprites
self.visible_sprites = visible_sprites
plr = self.image.get_rect()
def input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.direction.y = -1
elif keys[pygame.K_DOWN]:
self.direction.y = 1
else:
self.direction.y = 0
if keys[pygame.K_RIGHT]:
self.direction.x = 1
self.collision("Horizontal")
elif keys[pygame.K_LEFT]:
self.direction.x = -1
else:
self.direction.x = 0
if keys[pygame.K_SPACE]:
Magic((self.rect.x + 50,self.rect.y),[self.visible_sprites],self.direction)
def move(self):
self.rect.x += self.direction.x * 5
self.collision('Horizontal')
self.rect.y += self.direction.y * 5
self.collision('Vertical')
def collision(self,direction):
global collided
global loc
if direction == "Horizontal":
if self.direction.x > 0:
for sprite in self.obstacle_sprites:
if self.rect.colliderect(sprite.rect):
self.rect.right = sprite.rect.left
if self.direction.x < 0:
for sprite in self.obstacle_sprites:
if self.rect.colliderect(sprite.rect):
self.rect.left = sprite.rect.right
if direction == "Vertical":
if self.direction.y > 0:
for sprite in self.obstacle_sprites:
if self.rect.colliderect(sprite.rect):
self.rect.bottom = sprite.rect.top
#print(sprite.rect.topleft)
for i in loc:
if sprite.rect.topleft == i:
collided = True
self.rect.top = sprite.rect.bottom
if self.direction.y < 0:
for sprite in self.obstacle_sprites:
if self.rect.colliderect(sprite.rect):
self.rect.top = sprite.rect.bottom
#print(sprite.rect.topleft)
for i in loc:
if sprite.rect.topleft == i:
collided = False
self.rect.bottom = sprite.rect.top
def update(self):
global plr
self.input()
self.move()
plr = (self.rect.x,self.rect.y)
#print(self.rect.x)
1