I’m new with Unity, trying to create a simple plataform game (just for testing) and i dont know the best way to avoid the jump spamming, the first way i saw is using this code, i set the layer of the tilemap as 8 and it works fine, except when the player is next to a wall, then here comes the problem, the collision with the wall allows the jump spam. I dont know how to solve it, there is a way to check specifically the collision of the ground with the “feet” of the player? Or should I use another function that i dont know?
pls help!
Ah the age old “How do I check if I’m grounded” question.
Imagine if instead of checking collision with your whole spite, you just checked his feet. This way he is only ‘grounded’ when colliding with something underneath him, and not grounded when colliding with a wall next to him.
There’s a tonne of different ways to do this, but probably the most common is to use an Overlap Circle below the player’s feet with a radius smaller than the width of the player. Have a look here and see if you can figure it out.
A more new-user friendly way might be to add a little CircleCollider2D trigger as a child object underneath the player, and have a separate script on that to detect the ground, and tell the player script that it is grounded. But this isn’t really a great solution when the player script itself can handle all the logic internally.
public ContactFilter2D groundFilter;
public bool IsGrounded => rb.IsTouching(groundFilter);
rb would be the rigidbody2d. In the editor you can define the angle range and LayerMask so if the ground’s normal is beyond the angle range it will no longer be considered ground.
The normal angle reffers to a vector at an exact 90 degrees to the surface of a plane.
In your exact sciario we’re talking about the surface a player has hit. Basing your ‘isgrounded’ check on the normal angle of the contact is essentially saying, any surface that’s mostly horizontal, and not including surfaces that are mostly vertical.
I admit I am not famiular with setting up the ContactFilter2D compoent Chris is suggesting, but is sounds like an absolutly brilliant way to do this. I assume in the inspector you’ll have some controls to decide at what angle the contact needs to be to be included in the filter.
In 2D angles go from 0 degrees which is facing right to 90 degrees which is up to 180 degrees which is left and 270 degrees for down. Make sure you check Use Normal Angle and then for ground, Min Normal Angle I use 45 and Max Normal Angle 135.