- Home /
Unity ignoring bool grounded
My character jumps when I press the spacebar. My code says that it can only jump if it is grounded however it is still jumping when not grounded.
I have set up a debug log for grounded and not grounded. So i can see that i am jumping while the debug log is saying that I am not grounded.
I found out the error. I have two other checks for each side of my character and the players collider is hitting both making my character jump when not grounded.
Answer by ethan-smith · Apr 26, 2015 at 09:35 AM
private float collidercentertoedge;
public float groundmargin = 0.05f;
private RaycastHit ground;
private bool Isgrounded;
void Start(){
CapsuleCollider collider = GetComponenet<CapsuleCollider>();
collidercentertoedge = collider.bounds.extents.y - collider.center.y;
}
void Update(){
Rigidbody body = GetComponenet<Rigidbody>();
if(Physics.Raycast(transform.position, -transform.up, out ground)){
Isgrounded = ground.distance <= collidercentertoedge + groundmargin;
if(Input.GetKeydown(KeyCode.Space) & Isgrounded){
JUMP CODE HERE
JUMP CODE HERE
OR
body.velocity.y *= jumpforce;
}
}else {
Isgrounded = false;
}
}
it checks using raycast to see if there is something beneath you. if there is then we get the distance from the center of the collider to the bottom of it and then add the ground margin (the margin is incase you fall into a pit and you aren't touching the ground but the sides of it are holding you up, like if you fell down a narrow cone. if this happens and you still cant touch then increase the margin variable) and checks to see if the distance from the cast position to the hit position is less than or equal to this. if it is then you are touching ground or are withing the variable "groudmargin" from the ground. if there is nothingbeneath you then the raycast = false and so does "isgrounded"
Your answer
Follow this Question
Related Questions
Jumping when not grounded 2 Answers
How to fix jumping from Unity2D tutorial? 2 Answers
Jump of 2d character is sometimes stronger. 1 Answer
2d grounded check problem? 3 Answers
Unity 2D Platformer: How to properly implement this ground check? 1 Answer