Bluva
Bluva

Reputation: 31

Why I can't move my character with a joystick in Python?

I'm trying to make my game be able to be played with a xbox one controller, I can make it shoot and exit the game but I'm having trouble with the axis (I've tried with the D-pad but it was the same)

EDIT: Now i can make it move but It's like a frame, and I need to move the axis multiple times to make it move, I want to hold the axis 1 and that the player moves smoothly and it always moves left for some reason.

This is the Player class:

class Player(pygame.sprite.Sprite):

    def update(self):
        self.speed_x = 0
    for event in pygame.event.get():
        if event.type == JOYAXISMOTION:
            if event.axis <= -1 >= -0.2:
                self.speed_x = PLAYER_SPEED
            if event.axis <= 1 >= 0.2:
                self.speed_x = -PLAYER_SPEED
            self.rect.x += self.speed_x

Upvotes: 1

Views: 229

Answers (1)

Kingsley
Kingsley

Reputation: 14916

The Joystick only gives you notice of changes to position. So if it's previously sent an event to say that the joystick's left-right axis is at 0.5, then joystick axis is still at 0.5.

So you probably need something like:

    PLAYER_SPEED = 7

    ...
    
    for event in pygame.event.get():
        if event.type == JOYAXISMOTION:
            if event.axis == 1:                              # possibly left-right
                player.speed_x = PLAYER_SPEED * event.value  
            elif event.axis == 2:                            # possibly up-down    
                player.speed_y = PLAYER_SPEED * event.value
     ...


     # In main loop        
     movePlayer( player.speed_x, player.speed_y )

How the axes map to up/down and left/right is dependent on the joystick type. So maybe you will need to reverse the mapping.

Upvotes: 2

Related Questions