Home > Blockchain >  How do I change character's image based on user's last input key?
How do I change character's image based on user's last input key?

Time:07-23

I can make my character run in left and right direction. I am trying to make my character look in certain direction based on user's input. If user's last command was 'a' or 'K_LEFT', then I would like to make him look in the left direction. Otherwise make him look in the right direction. I don't know how to achieve this. I looked up at KEYUP in pygame documentation, but I wasn't able to understand it. Could someone help me here? Here is the code -

def animate_char(self):

        keys = pygame.key.get_pressed()
        is_resting_forward = True
    if self.rect.bottom != 470:
        self.image = self.player_jump

    elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
        self.hero_index  = 0.15
        if self.hero_index >= len(self.images_runf_list):
            self.hero_index = 0
        self.image = self.images_runf_list[int(self.hero_index)]
    elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
        self.hero_index  = 0.15
        if self.hero_index >= len(self.images_runb_list):
            self.hero_index = 0
        self.image = self.images_runb_list[int(self.hero_index)]
        is_resting_forward = False

    else:
        if is_resting_forward:
            self.image = self.image_restf
        else:
            self.image = self.image_restb

I am not getting what I wanted from this code. The character sets the value of self.image_restf everytime I lift any key.

CodePudding user response:

is_resting_forward must be an attribute of the class. Set the attribute depending on the pressed key:

def __init__(self, ......):
    # [...]

    self.is_resting_forward = True
def animate_char(self):

    keys = pygame.key.get_pressed()

    if self.rect.bottom != 470:
        self.image = self.player_jump

    elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
        self.hero_index  = 0.15
        if self.hero_index >= len(self.images_runf_list):
            self.hero_index = 0
        self.image = self.images_runf_list[int(self.hero_index)]
        self.is_resting_forward = True

    elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
        self.hero_index  = 0.15
        if self.hero_index >= len(self.images_runb_list):
            self.hero_index = 0
        self.image = self.images_runb_list[int(self.hero_index)]
        slef.is_resting_forward = False

    else:
        if self.is_resting_forward:
            self.image = self.image_restf
        else:
            self.image = self.image_restb
  • Related