How to prevent character from being able to jump in midair?

So I've been playing around with box2d on iOS (thought this question isn't really limited to iOS), and I've got a small demo going where a player character jumps when the user taps the screen via ApplyLinearImpulse.

For the most part, it works. Except if I tap while the player is in midair, ApplyLinearImpulse is called again, and the player "jumps" again, but in midair. Now, it'd be pretty neat to do that in real life, but you can't, and I'd prefer my player not be able to do that either.

So I've been trying to come up with a decent way to prevent jumping while a player is already jumping, and I'm not sure where to go from here - my best thought is to try something like this:

    -Attach a body that is just a sensor to the bottom of my player with a fixed joint.
    -When the player jumps, disable jumping until the aforementioned sensor detects a collision (i.e., when the player "lands" on something, which may or may not be the ground).
    -Once a collision has been detected, re-enable jumping.

I'm not sure how much I like this idea, for one, I'm not sure if attaching a sensor to the bottom of my player is the "smartest" way of detecting collisions on the bottom of my player sprite. I haven't given this a try yet, I wanted to instead get others' input on it and see if anyone could provide a better alternative. Any ideas?

Edit: I've had a suggestion from someone that I should try some sort of downward hit test, using a ray straight downward from the bottom of my player's body, and see if that ray intersects another object within a short distance (i.e., right below my player) - is that type of ray-casting hit test possible with box2d?
Hi there!

I am currently working on a sidescroller on iOS using box2d. I had the same problem as you, however the solution I found has nothing to do box2d.

You could easily add some type of flag to figure out if your character should jump or not, for instance:

Code:
BOOL characterShouldJump = true;
float verticalImpulse = 10.0f;

if (characterShouldJump == true) {
   body->ApplyLinearImpulse(b2Vec2(0.0f, verticalImpulse));
   characterShouldJump = false;
}


Then you would have to find a way to reset your characterShouldJump back to true, somehow.

However, if your character can perform many actions, using flags will become troublesome. You will have a bunch of if, else spread around your code. This can be solved using a Finite State Machine.

This is the approach I've chosen for my game. You can look it up on the web, however I'll give you some example code.

The basic idea behind a Finite State Machine is that you define the states of the character and the transitions that can happen between states.

Let's say a character can be in three different states. He could be standing still, running or jumping!

A character who is standing still could perform a jump, or start running. However, he should not be able to start running as he is jumping and he should not be able to perform a jump if he is already performing a jump!

To solve this problem we will define specific states for our character. But first we to define a base state that all our states can inherit from.

This would be the base class for your states:
Code:
@interface CharacterState : NSObject
{
   // reference to the character
   Character* myCharacter;
}

- (id)initWithCharacter:(Character*)aCharacter;
- (void)enter;
- (void)update:(float)deltaTime;
- (void)exit;

@end

@implementation CharacterState

- (id)initWithCharacter:(Character*)aCharacter
{
   [super init];
   
   myCharacter = aCharacter;
   
   return self;
}


A JumpingState would look something like this:

Code:
@interface CharacterJumpState : NSObject
{
   float verticalImpulse;
}

@end

@implementation CharacterJumpingState

// And this would be the implementation
- (void)enter
{
   // Make the character jump
   character.body->ApplyLinearImpulse(0.0f, verticalImpulse);
}

@end


You can then go on defining other states for your characters such as...

Code:
@interface CharacterStandingStillState : CharacterState
{
   
}

@end

@interface CharacterRunningState : CharacterState
{
   float runningSpeed;
}

@end

etc...

Your character will be in charge of keeping track of it's current state and swapping between states when collisions with the floor, with enemies, etc, happen.

Lets say a touch on the screen triggers a jump. It would then call the performJump character's method. The collision with the floor would call the standStill character's method. Here's an example:
Code:
@interface Character : NSObject
{
   CharacterState* currentState;
   b2Body* body;
}

@end

@implementation Character

- (id)init
{
   [super init];
   
   currentState = [[[CharacterStandingStillState alloc] initWithCharacter:self] retain];
   
   return self;
}

- (void)performJump
{
   // If the character is not jumping, switch to jumping state
   if (![currentState isKindOfClass:[CharacterJumpState class]]) {
      [currentState exit];
      [currentState release];
      
      currentState = [[[CharacterJumpingState alloc] initWithCharacter:self] retain];
      
      [currentState enter];
   }
}

- (void)standStill
{
   // This method will be called when the character collisions with the floor
   
   [currentState exit];
   [currentState release];
      
   currentState = [[[CharacterStandingStillState alloc] initWithCharacter:self] retain];
      
   [currentState enter];
}

- (void)update:(float)dt
{
   [currentState update:dt];
}

- (void)dealloc
{
   [currentState exit];
   [currentState release];
   
   [super dealloc];
}

@end


Finally, here's how I would go about checking collisions between the floor and my character. Box2d asks you to extend the b2ContactListener class in order to define the actions to perform when a collision happens:

Code:
class MyContactListener : public b2ContactListener  {
   
private:
   void BeginContact(b2Contact* contact);
   void EndContact(b2Contact* contact);
   void PreSolve(b2Contact* contact, const b2Manifold* oldManifold);
};

void MyContactListener::BeginContact(b2Contact* contact) {
   // First you retrieve both bodies and then their userData
   b2Body* aBody = contact->GetFixtureA()->GetBody();
   b2Body* anotherBody = contact->GetFixtureB()->GetBody();
   id anEntity = aBody->GetUserData();
   id anotherEntity = anotherBody->GetUserData();
   
   // Then you find out their class
   if ([anEntity isKindOfClass:[Character class]] && [anotherEntity isKindOfClass:[Floor class]]) {
      [(Character*)anEntity standStill];
   }
   else if ([anEntity isKindOfClass:[Floor class]] && [anotherEntity isKindOfClass:[Character class]] {
      [(Character*)anotherEntity standStill];
   }
}


This sure looks clean!

As I said before, this is a very basic and crude way of implementing states for your character. In my case, I use a more complex system since I have several different states that can run concurrently.

I hope this help, even if you find a solution using box2d and flags, know that FSM can make save you a lot of time when debugging your game or implementing additional behavior for your character.
Hey soulstriderx, thanks for the reply! I've considered a FSM for the states my player will eventually be in, but that isn't really the focus of my question (thought I do appreciate your thoughts on the subject, I'll definitely take them into consideration).

You mentioned this, however:
Quote:
Your character will be in charge of keeping track of it's current state and swapping between states when collisions with the floor, with enemies, etc, happen.

Lets say a touch on the screen triggers a jump. It would then call the performJump character's method. The collision with the floor would call the standStill character's method. Here's an example:


The line in your text that I've bolded is my concern. How do I know the player collided with the floor? What if he collided with something in midair, on the top of the player sprite, or on it's side (i.e., not the bottom of the player sprite)? What if he landed on a box that happens to be resting on the floor?

That's my current dilemma- how do I detect the specific condition of my player landing on something, whether that "something" is the ground, or a box that is sitting on the ground?

The collision detection code you added is helpful, but I think it still has a potential flaw - if my player jumps towards a wall (that the player could, in theory, land on), and he happens to hit the side of the wall, the player would then be eligible again to "jump" - i.e., the player would be in a standstill state when the player should not be.
Yes, I'm sorry!

I figured that out just as I sent the reply, but I edited the post and added the contact listener portion, hope it helps!

PD: If you are wondering how I retrieve the character and floor objects from the user data, you simply define it when you are creating the bodyDef for your body:

Code:
b2BodyDef bodyDef;
bodyDef.userData = (void*) self; // self refers to Character
bodyDef.position = p2v(position) * world.ptmRatio;
bodyDef.angle = rotation;
bodyDef.type = b2_dynamicBody;
@soulstriderx, on a side note, I do really like your FSM implementation, by the way. Thanks for that - that will be very useful 🙂
zwangaman wrote:
The collision detection code you added is helpful, but I think it still has a potential flaw - if my player jumps towards a wall (that the player could, in theory, land on), and he happens to hit the side of the wall, the player would then be eligible again to "jump" - i.e., the player would be in a standstill state when the player should not be.


It depends how you define your edges, your states, etc. It's definitely something to consider, though.

My character goes from running to jumping, then to falling and finally to running again. I don't have walls, so it's not something I've thought about!
Quote:
It depends how you define your edges, your states, etc. It's definitely something to consider, though.


Hmm, that gets me thinking - maybe I could have a thin, horizontal sensor on top of objects that my player can stand on. Although that doesn't really work if the objects can rotate - for example, a box can be picked up and thrown, and can land in any orientation, and potentially stay there....

No, scratch that - back to the drawing board 🙂
I have a solution, after finally getting a chance to play around with box2d this evening. The solution is to use b2World::RayCast() - basically, each frame, fire a ray from the center of my player to a point just barely below the player. If the ray intersects with anything, the player can be said to be "resting on something" - that condition is what I can use to determine if my player is allowed to jump again.
That's a good solution. What happens, though, if mid-jump, another object crosses the path of the raycast (like a bullet being fired by an enemy, for example)? You would be able to perform a mid-air jump. Maybe this is design intended (the player is able to jump on top of bullets), but maybe not! Something I was thinking about was this:

You could check for the player's linear velocity on the Y coord. If it's 0 it could mean two things, he's either standing still, or at the apex of his jump. Maybe use this to figure out the state?

For example:

Code:
- (void)update:(float)delta
{
   if (player.linearVelocity.y < 0)
      [player switchToState: @"Falling"];
   
   
   if (player.linearVelocity.y == 0)
   {
      if (player.currentState == @"Falling")
         [player switchToState: @"StandingOnTheGround"];
   }
}

- (void)performJump
{
   if (player.currentState == @"StandingOnTheGround")
      [player switchToState: @"Jumping"]; // internally, you apply the impulse
}


The only way to end up back in StandingOnTheGround State is through the FallingState. This way you don't even need to check collisions at all!
Quote:
What happens, though, if mid-jump, another object crosses the path of the raycast (like a bullet being fired by an enemy, for example)? You would be able to perform a mid-air jump. Maybe this is design intended (the player is able to jump on top of bullets), but maybe not!


Hmmm.... that's a good point. In my game, I think that's pretty unlikely - I may not even have the concept of bullets - but, I'm not decided, and if I do, that's a potential flaw.

I think you're definitely onto something with checking the player's linear velocity on the Y axis - maybe a combination of the two techniques would reduce the chance of an "illegal jump":

Each frame:
    1) Cast a downwards ray, determine if there is something directly below player
    2) If so, check linear velocity on the Y axis - if it's zero, consider the player in a legal jumping state

I think we'd have to play around with that, but it seems decent to me - or, at least, decent enough for a game 🙂

Original thread: https://box2d.org/forum/viewtopic.php?t=6803