- Home /
The question is answered, right answer was accepted
IsGrounded does not work
Sooo, I am trying to check if my 2D "Player" is grounded or not.
Following code excerpts:
// Use this for initialization
void Start () {
float distanceToGround = GetComponent<Collider2D>().bounds.extents.y;
}
And the isGrounded function is following:
bool isGrounded()
{
return Physics2D.Raycast(transform.position, -Vector2.up, distanceToGround + 0.1f);
}
But it is telling me 24/7 that distanceToGround does not exist in the current context...
My player is using a polygon collider2d and a rigidbody 2d. I just want to prevent my player from jumping while he is "jumping"/not grounded...
Greetings
Answer by robert_southee · Mar 17, 2015 at 10:14 AM
You're declaring distanceToGround inside Start(), which means that the function isGrounded() doesn't know about it. What you want is:
float distanceToGround;
// Use this for initialization
void Start () {
distanceToGround = GetComponent<Collider2D>().bounds.extents.y;
}
bool isGrounded()
{
return Physics2D.Raycast(transform.position, -Vector2.up, distanceToGround + 0.1f);
}
Ah damn... thank you that worked. But now it is returning true everytime, even if my player is in the air... How can I fix that?
Physics2D.Raycast - "this will also detect Collider(s) at the start of the ray". There is another overload of Physics2D.Raycast that takes a layer$$anonymous$$ask, you can put the "ground" onto a different layer, have a public variable on your script that takes a Layer$$anonymous$$ask and pass that to the Raycast method.
Answer by NerdRageStudios · Mar 17, 2015 at 09:50 AM
Could you look to see if velocity is not equal to 0?
http://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
Thanks, I tried it and it was also a comfortable solution.
Answer by Deathtruth · Mar 17, 2015 at 01:28 PM
distanceToGround will only be accessible in the Start() function since that is where it is decleared.
Declear it at the top of your script outside of the start function.