Raycating Terrain Normal Problems

Here’s the deal. I have some code that allows me to rotate a car to the terrain normal. Here it is:

var rotSpeed = 1;

function Update () {
	transform.Rotate(0, 0, Input.GetAxis("Horizontal") * rotSpeed);

	var hit : RaycastHit;
	
	if (Physics.Raycast (transform.position, -Vector3.up, hit, 5)) {
		var rot = Quaternion.FromToRotation(Vector3.forward, hit.normal);
		transform.rotation = rot;
	}
}

Now, the car does form to the terrain, but when I hit my left and right buttons, it does not rotate. I think it is because I’m setting the rotation to “rot” in every frame.

I know the axises seem a bit odd, but that is because I have to set my X-axis to 270 because my modeling program exports my models like that.

You might want to parent your model to an empty gameobject which has y-up and z-forward and work with the properly aligned gameobject instead of the car, that would simplify things a bit.

Good idea, but I have a mesh collider and code in the script that calls for action when the car collides with something. And I really would like to keep it all in one gameObject if possible.

The issue with your script is that you are rotating using transform.Rotate, then later setting the rotation - the second assignment overrides the first.

This is actually a little bit trickier than it looks. You need to maintain the accumulated rotation of the object, then get the alignment with the normal and combine the two rotations using quaternion multiplication:-

var rotSpeed = 1.0;
var upTarget: Transform;
var accumTurn: Quaternion = Quaternion.identity;
	
	
function Update () {
	var hit : RaycastHit; 
 
	if (Physics.Raycast (transform.position, -Vector3.up, hit, 5)) { 
		var alignRot = Quaternion.FromToRotation(Vector3.forward, hit.normal);
		accumTurn *= Quaternion.AngleAxis(Input.GetAxis("Horizontal") * rotSpeed, Vector3.forward);
		transform.rotation = alignRot * accumTurn;
	}
}