简体   繁体   中英

Moving a sprite with pygame

this is the code for my Character class:

right = [2, 0]

class Character(pygame.sprite.Sprite):
    def __init__(self):
        super(Character, self).__init__()

        self.image = pygame.image.load("character_n.png").convert()
        self.image.set_colorkey((25, 25, 25))

        self.rect = self.image.get_rect()

char = Character()

char.rect[0] = 375
char.rect[1] = 400

And the code in my game loop that moves the character to the right if the joystick is moved to the right:

h_axis_pos = my_joystick.get_axis(0)
v_axis_pos = my_joystick.get_axis(1)

if h_axis_pos >= 0.50:
    if char.rect.right < 800:
       char.rect = char.rect.move(right)

This code worked fine when the character was a simple image, but does not work now.

I am confused, since self.rect is initialized and the character is set at the coordinates I selected. I tried to use char.rect[0] in the if and increment it, but still the same error appears:

if char.rect.right < 800:
AttributeError: 'pygame.Surface' object has no attribute 'rect'

Can someone shed some light on this? Thanks.

In this bit of code:

 if char.rect.right < 800:
      idle = 0
      char.rect = char.rect.move(right)
      char = pygame.image.load("right_n.png")

In the line:

char = pygame.image.load("right_n.png")

You are overwriting your char and assigning a pygame.Surface to it. So on the next iteration of the game loop it fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM