Reputation:
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)
Upvotes: 2
Views: 59
Reputation: 210909
Draws the contained Sprites to the Surface argument. This uses the
Sprite.image
attribute for the source surface, andSprite.rect
for the position.
Therefore you need to update the rect
attribute after changing the position (pos
) of the Sprite:
class Sprite(pygame.sprite.Sprite):
def __init__(self, pos):
super(Sprite, self).__init__()
self.image = demon
self.pos = [pos[0], pos[1]]
self.rect = self.image.get_rect(center = pos)
def update(self, moveX, moveY):
Sprite.pos[x] += moveX
Sprite.pos[y] += moveY
self.rect = self.image.get_rect(center = pos)
You don't actually need the pos
attribute at all. You can move the Sprite by changing the position stored in rect
:
class Sprite(pygame.sprite.Sprite):
def __init__(self, pos):
super(Sprite, self).__init__()
self.image = demon
self.rect = self.image.get_rect(center = pos)
def update(self, moveX, moveY):
self.rect.x += moveX
self.rect.y += moveY
Additionally update
is an instance method. You need to call it with the object instead of the class:
if keys[pygame.K_w]:
my_sprite.update(0, 50)
if keys[pygame.K_s]:
my_sprite.update(0, -50)
if keys[pygame.K_d]:
my_sprite.update(50, 0)
if keys[pygame.K_a]:
my_sprite.update(-50, 0)
Upvotes: 1