- Home /
Question by
JSmithsonian · Feb 17, 2016 at 09:42 PM ·
rigidbodyraycastisgrounded
How to check if rigidbody is grounded with raycasts on uneven surfaces?
I am currently checking if I am on ground with a short raycast from the transform.position of my character. This works fine on even surfaces and even while going up slopes. But it doesn't work at all when you try to go down a slope. The character constantly goes midair when I try to go down a slope.How can I solve this issue.This is the code that is being used currently:
bool Grounded()
{
return Physics.Raycast(transform.position, Vector3.down, moveSettings.distToGround, moveSettings.ground);
}
Comment
Answer by toddisarockstar · Mar 23, 2017 at 04:39 PM
I use this script. it works magically. it simply shows grounded if your guy is touching anything with a name containing "floor". if you dont want to rename you terrain i added an alterative code at the bottom to check if the contact point is below a certain height on the collider to detect instead.
int i;
int touch;
int ot;
int pad;
bool yes;
bool sw;
GameObject p;
public bool grounded;
public int framepad;
//the frame pad variable is the amount of frames delay before "grounded" is set back to false
//incase your character slightly bounces or something
void Update () {
if (touch != ot) {if(touch>20){touch=0;}
ot=touch;pad=1+framepad;}
else{if(pad>0){pad--;}}
if(pad>0){grounded=true;}else{grounded=false;}
}
void OnCollisionStay(Collision c) {
//i reccomend just naming your terrain to floor
if (c.transform.name.Contains("floor")) {touch++;}
// alteratively you dont want to name your
// floors, you could do it like below instead to see if the contact point
// is below a certain height on your character hopefully the bottom of you guy is round
// otherwhise it will trigger walls. you could of course put this script on a seperate collider for
// your feet:)
bool b = false;
i = c.contacts.Length;
while(i>0){i--;
//fine tune the nubmer in the next line
//it sets the up/down cuttoff for where your feet are on the collider!!!
if(c.contacts[i].point.y<transform.position.y+.01f){b=true;}
}
if (b) {touch++;}
}