- Home /
Check if 2D Player is grounded with Physics2D.Linecast
Hi, mates,
I'm feeling a bit desperate because last 2 hours I've spent searching for a solution, but didn't succeed. I tried to develop an easy script to check if the Player isGrounded.
But the problem is that when I run the project my player is "floating" in the air, like no gravity is applied. (Rigidbody2D is attached)
###upd: I've increased the Gravity Scale of the player, so he finally landed, but the script still does not set grounded = true, i guess the problem is in the Physics.Linecast()
Code where I try using the Linecast function never sets grounded or jump to true
void Update()
{
myMaskLayer = 1 << LayerMask.NameToLayer("Ground");
grounded = Physics2D.Linecast(transform.position, groundCheck.position, myMaskLayer);
if(Input.GetButtonDown("Jump") && grounded){
jump = true;
}
}
A screenshot with configurations from Unity
Thank you!
Double check if the gravity value in the editor is set to the default, and try to increase the Gravity Scale or the $$anonymous$$ass of the object.
The gravity value is ok. Also I increased the Gravity Scale to 15, the player grounded, but the variable grounded inside the Update() is still false. I guess something is wrong with the Linecast()
Try to make the grounded var as a public then you can control easily and see what is happen in the inspector.
I print the value of the variable grounded to the console, it's not the main issue
I have something wrong with the "basic" gravity options and can't figure why
Answer by Sparkline · Feb 20, 2014 at 09:40 PM
I'm not sure what is groundCheck in your scene, but maybe my code will help:
hitDown = Physics2D.Linecast(transform.position, new Vector2(transform.position.x, transform.position.y - 25), 1 << 9);
distanceDown = Mathf.Abs(hitDown.point.y - transform.position.y); if(distanceDown > (boxCollider.size.y/2)) { inAir = true; } else { inAir = false; }
Here is casting line 25 units down, calculating a distance, and if the distance is larger than the height of BoxCollider2D attached to player than that means we are in air (or grounded = false in your case).
P.S. comparing with half of collider works better if collider is in center of object. In other cases you can get needed value with debuging distance.