InfernoKay
InfernoKay

Reputation: 43

Python Platformer: Jumping Characters

For one of my projects, I am trying to make it such that if I tap w, it jumps, but if I hold, it gets a bit of a boost and jumps higher.

However, I do not want it to jump after I let go, but during this duration.

I am using pygame.math.Vector2 for the movement vectors, with acceleration and velocity set up. When I jump it applies an acceleration, and I have gravity pulling it down.

Thanks for the help!

(If I am unclear just tell me, I am not very good at explaining things... :/)

Upvotes: 2

Views: 292

Answers (2)

Mercury Platinum
Mercury Platinum

Reputation: 1569

Im not sure if checking if a key is held/tapped is possible in pygame, but you could always bind the two types to different keys.

If you are using pos vectors and a gravity variable, this collision code will work wonders. Make sure to set on_ground to False whenever you jump too.

    self.pos.x += self.vel.x * dt
    self.rect.x = self.pos.x

    collisions = pg.sprite.spritecollide(self, self.blocks, False)
    for block in collisions:
        if self.vel.x > 0:
            self.rect.right = block.rect.left
        elif self.vel.x < 0:
            self.rect.left = block.rect.right
        self.pos.x = self.rect.x

    self.pos.y += self.vel.y * dt
    self.rect.y = self.pos.y

    collisions = pg.sprite.spritecollide(self, self.blocks, False)
    for block in collisions:
        if self.vel.y > 0:
            self.rect.bottom = block.rect.top
            self.vel.y = 0
            self.on_ground = True
        elif self.vel.y < 0:
            self.rect.top = block.rect.bottom
            self.vel.y = 0
        self.pos.y = self.rect.y

    if self.rect.bottom >= WINDOW_HEIGHT:
        self.vel.y = 0
        self.rect.bottom = WINDOW_HEIGHT
        self.pos.y = self.rect.y
        self.on_ground = True
    else:
        self.vel.y += GRAVITY * dt  # Gravity

P.S Check the below question for the keypress answer.

Upvotes: 1

Jose L. Reyes
Jose L. Reyes

Reputation: 36

What you could do is use some type of time variable to check how many milliseconds the "W" character is being held down. If it's just pressed, then it will only jump once, but if the key is being held for, let's say 800 miliseconds, then instead of just jumping, you would do a high jump or boosted jump.

Here is some sudo code:

# this variable will keep track of your time
# look for an online time library for python
time = 0;

# Check for "W" key and duration of press
if keypressed = w: 
    if time < 800 miliseconds:
        # Execute normal jump
    else:
        # Execute boosted jump

Upvotes: 2

Related Questions