- Home /
What's a good way to find the ground normal?
I'm gonna be kinda abstract about this question this time.
What's a good way to find the normal of the ground a character is standing on?
Check Aldo's answer to this :
http://answers.unity3d.com/questions/179095/how-to-make-a-enemy-bleed.html#answer-179132
basically the .normal
But the .normal of which collision? A character could be touching multiple surfaces at a given moment.
So ray cast from the position of the character in -transform.up and get the normal from the raycast hit... Or -Vector3.up and get the pure normal of that location.
How far would one have to raycast? Depending on the slopes, a downward raycast would have to extend very far. Then in cases of flat surfaces, it would detect ground far below the character.
You can ray cast using an infinite distance but use a layer mask to avoid raycasting a lot of objects. Perhaps put your terrain in a Terrain layer and just look for that in Vector3.down like whydoidoit said
Answer by aldonaletto · Dec 04, 2012 at 01:16 AM
You could cast a ray in the -transform.up direction or in the Vector3.down direction, as @whydoidoit said. Vector3.down gives the normal of the surface below the character position, while -transform.up returns the normal under the character feet. The raycast range may be a little longer than the distance from the character pivot to its feet in order to compensate for inclined surfaces. You must decide what to do when the ground is out of the raycast range: you can keep the last surface normal or assume the world up direction (Vector3.up).
This is a simple code to find the normal under the character feet; if no ground is hit, the last normal is kept:
private var distToGround: float;
private var normal: Vector3 = Vector3.up;
function Start(){
distToGround = collider.bounds.extents.y - collider.center.y;
}
function Update(){
// assume a range = distToGround + 0.2
if (Physics.Raycast(transform.position, -transform.up, hit, distToGround + 0.2)){
normal = hit.normal;
}
}
If you want to use the ground normal to make a character that aligns to the ground, take a look at the question Orient vehicle to ground normal. If you want a character that walks on any surface, take a look at the question Basic Movement. Walking on Walls.