Raycast align with ground normal

I felt this was a better place to ask this, rather than the forums. Ok, so I have a car that I can move around and I need it to align itself to the ground normals for a Mario Kart/Little Big Planet Kart type of physics. The script I have has some problems. Whenever it “aligns” me to the ground normals it sets my Y rotation to the specific rotation every time. It also doesn’t align me often enough. It usually only works when I go up and down slopes. It is in the Update, so that’s not the problem.
Here is my script so far:

	var hit : RaycastHit;
    var castRot = Vector3(transform.position.x,transform.position.y-.50,transform.position.z);
    if (Physics.Raycast (castRot, -transform.up, hit)) {
        transform.rotation = Quaternion.FromToRotation (Vector3.up, hit.normal);
    }

Does anybody have an idea of what is wrong?

You could also try setting transform.up = hit.normal. What you don't want to do is set the rotation to just that FromTo as @robertbu says - you would want to modify the existing rotation. transform.up = hit.normal does try to do that.

Ok, is this right? var hit : RaycastHit; var castRot = Vector3(transform.position.x,transform.position.y-.50,transform.position.z); if (Physics.Raycast (castRot, -transform.up, hit)) { prevNormal = hit.normal; Quaternion q = Quaternion.FromToRotation(prevNormal, hit.normal); transform.rotation = q * transform.rotation; It says ';' is expected on the line, "Quaternion q = Quaternion.FromToRotation(prevNormal, hit.normal); ". Can you not declare Quaternion variables like this?

2 Answers

2

My answer to this question shows a script that aligns a CharacterController vehicle to the ground (aligns its transform, not the CharacterController: the CC is always upright). This script works fine for regular terrains, but may fail when the terrain steepness is too high, specially if it turns upside down. For a more generic case that can handle vertical or upside down surfaces, take a look at my answer to this question - it uses a rigidbody instead of a CharacterController, which may be more convenient for a vehicle.

So far I've tried the first one and it works REALLY well. It will need a bit of tweeking for my own purpose, but it's great! Since you said the other one would be better for rigid bodies, I'll try it out tomorrow and get back to you! I had seen the first one before, but never tried it. Pretty dumb of me. I have to thank you, as I've been trying to make this work for weeks! Also, I've thought about using a character controller for a vehicle. What do you think about them for a Kart game like I'm trying out?

I found transform.up-=(transform.up-hit.normal)*.1; to work really well.