piriTV
piriTV

Reputation: 19

Unity Player jump: when to use RaycastHit and when OnCollisionEnter

I am currently learning Unity with C# and now learned two ways to perform a player jump with double jump prevention.

The first is the GetComponent<Rigidbody>().AddForce method with double jump prevention by OnCollisionEnter, e.g. on transform.tag == "Floor".

The second is with the RaycastHit and Velocity for up.

For me the second method didn't work quite well. I was still able to do a double jump.

I was now wondering if someone could explain to me why or when to use one method above the other or which might be superior.

Thanks in advance!

Upvotes: 1

Views: 918

Answers (1)

HumanWrites
HumanWrites

Reputation: 945

Neither approach is necessarily superior. It all depends on the needs of your game.

Using a well-placed collider at the "feet" of a player model to check for groundedness can work well, but the emphasis is on "well-placed". Poorly positioned or poorly sized/shaped colliders will lead to false positives/negatives. For example, a player may hit the underside of a "ground" platform in the sky and set grounded to true. Or if a player is standing on the very edge of a platform their ground-check collider may not be colliding with the surface they are standing on, causing grounded to be false. And many other edge cases.

Using raycasting gives far more precise control over when and where groundedness should be checked, however, it is more expensive from a processing perspective. Raycasting also allows for upcoming ground collisions to be checked for.

A sophisticated system might use both raycasting and collision detection to cover all necessary groundedness cases.

Upvotes: 1

Related Questions