I'm trying to play around with pygame and I can draw an image as a sprite on the screen. I'm trying to move the sprite around with WASD by changing the x and y variables.
When I run the program, the sprite draws but doesn't move when I press the correct keys.
EDIT: I added an update method and the moveY param is saying it is not there, even though it clearly is, why is this?
Here's the code:
import pygame
pygame.init()
screen = pygame.display.set_mode((750, 750))
BLACK = (0, 0, 0)
WHITE = (255,255,255)
RED = (255,0,0)
class Sprite(pygame.sprite.Sprite):
def __init__(self, pos):
super(Sprite, self).__init__()
self.image = demon
self.pos = [x,y]
self.rect = self.image.get_rect(center = pos)
def update(self, moveX, moveY):
pygame.sprite.Sprite.update(self)
moveXY = [moveX,moveY]
Sprite.pos[x] += moveXY[moveX]
Sprite.pos[y] += moveXY[moveY]
all_sprites_list = pygame.sprite.Group()
demon = pygame.image.load("C:/programming/doomman/cacodemon.png").convert_alpha()
x = 300
y = 300
my_sprite = Sprite((x, y))
all_sprites_list.add(my_sprite)
clock = pygame.time.Clock()
pygame.display.set_caption("Demon Dance")
carryOn = True
while carryOn == True:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
elif event.type == pygame.KEYDOWN:
if keys[pygame.K_w]:
Sprite.update(0, 50)
if keys[pygame.K_s]:
Sprite.update(0, -50)
if keys[pygame.K_d]:
Sprite.update(50, 0)
if keys[pygame.K_a]:
Sprite.update(-50, 0)
pygame.display.flip()
clock.tick(60)
all_sprites_list.draw(screen)
my_sprite = Sprite((x, y))x and y are copied to the function. That means that when you change the value of x or y it doesnt get reflected in my_sprite. Is there a method for modifying the sprite object directly? - lvrfupdatemethod for the sprite. I would recommend looking into that and modifying your x and y coords by calling said method: pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite - lvrf