# How to manage "jump" in my 2d platform game?

I'm developing a simple 2d platform game with Unity 2d. I have a problem managining my "Jump" action for the player.

I would like the player to Jump only when he has his feet on a "surface": terrain, platform, crate etc. I'm considering using colliders: when my player collides with a surface, set my bool canJump = true. When he jumps, I set canJump = false (he is midair).

My terrain has a Rigidbody2d is Kinematic and a Box Collider 2d. My Player has a Rigidbody2d is Dynamic and a Capsule Collider 2d (or a Polygon Collider.. )

The events OnCollisionEnter2d() and OnTriggerEnter2d() are never raised when Player collides with terrain.

Does anyone know what's wrong?

Thanks

EDIT: Now i'm using this to check if "something" is under my feet:

RaycastHit2D hit = Physics2D.Raycast(rb.transform.position, -Vector2.up, 0.1f);
if (hit)
canJump = true;


It doesn't works! hit is always true! I'm getting mad!

• I tend to use colliders for checking jump, just checking if the player is touching the ground, and if they are then they can jump. You do not need a rigidbody on both things in order for onCollisionEnter to work, only one of the two things needs the rigidbody. Feb 3 '17 at 16:14
• Yes I know. The problem is that neither OnCollisionEnter2D and OnTriggerEnter2D is raised .. also without rigidbody on my Terrain ... Feb 3 '17 at 16:34
• Only a hint, Physics2D.CircleCast usually works better (often) when checking if a player is grounded. Feb 3 '17 at 17:12
• How are you moving your player character at present? If you're repositioning them with transform.position = or transform.Translate() this can effectively "teleport" the object from one side of the trigger boundary to the other, so the physics engine never sees the contact happen and never fires the OnCollisionEnter2D/OnTriggerEnter2D events. Moving the object via the Rigidbody2D usually solves this. There could also be issues with the object hierarchy, where the collider that receives the collision event doesn't pass it on to your script, so showing your player character's setup will help. Feb 3 '17 at 17:22

## 1 Answer

Your way should work, however I believe that the raycast is colliding with itself. You could start the raycast below the player.

However, a better way would probably be to use the colliders combined with the state machine.

When the player comes in contact with the ground (onCollisionEnter..), set a bool/animation state(standing or something) to mark that they are on the ground. When they jump, you can set the animation to a jumping animation and set your upward force.

Then, disallow further jumping (or add a counter for things like double jumping) if the flag/state from above is not set.

You can reset the flag/animation when you collide with the ground again.

• You're right. My problem was that raycast was colliding with Player... ! Thanks Feb 4 '17 at 9:34