简体   繁体   中英

LibGDX - How to control touch events for Jumping multiple times

I am working on a Game with LibGDX and I am trying to figure out how to limit the TouchEvent for Jumping.

MY ATTEMPT:

if(player.b2body.getLinearVelocity().y > 3.5f){
            float currentVelocityY = player.b2body.getLinearVelocity().y;
            player.b2body.applyLinearImpulse(new Vector2(0, (- currentVelocityY)), player.b2body.getWorldCenter(), true);
    }

I was thinking of reducing the velocity on Y axis if it overreaches some value. But this does not work, as if I keep touching the screen, the character will fly higher.

I want to limit the touchEvent for jump only to two times within short time.

Any ideas of yours?

Thanks.

Solution 1 (limit the jumps per second):

So, your character jumps on touchDown event. You define a variable to store the last tap in milliseconds:

long lastTap = System.currentTimeMillis();

And on the tap event:

public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
  if(System.currentTimeMillis() - lastTap < 1000) 
    return true;

  // your character jump code

  lastTap = System.currentTimeMillis();
  return true;

This should call your jump code only once per second (because of the 1000ms in the if) no matter how quick you tap. Just test with the number (500 will we 2 taps per second, 250 - 4, etc..).

Solution 2 (limit the jumps count):

You define a variable to store how many times a jump was performed and the max jumps count:

int jumps = 0;
int maxJumps = 3;

And on the tap event:

public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
  // the limit is reached
  if(jumps == maxJumps) 
    return true;

  // your character jump code

  jumps++;
  return true;

And you reset the jumps var on your render() method or in the box2d interaction listener of your character when the body falls:

if(player.b2body.getLinearVelocity().y == 0)
    jumps = 0;

Now the user will be able to do a 3 fast jumps and then he will have to wait for the character to fall on the ground to jump again.

Solution 3 (check for the force on tap)

public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
  if(player.b2body.getLinearVelocity().y > 3.5f) 
    return true;

    // your character jump code

    return true;
}

Now the user will be able to jump as long as the y velocity is under 3.5f.

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