Using hit.normal w/ FromToRotation forcing Y to always be 0

I implemented a terrain follow script and am having difficulty in setting the GO on the Y-axis to anything other than 0 as the script always sets the Y-axis to 0. The script looks like this:

var fwd:Vector3 = transform.TransformDirection(Vector3.forward);
		
transform.position += fwd/speedModifier;
		
var hit:RaycastHit;
if (Physics.Raycast(transform.position, -transform.up, hit, 10)){
		
	if ( hit.distance > 1 ){
		transform.position.y -= hit.distance-1;
	} else if ( hit.distance < 1 ){
		transform.position.y += 1-hit.distance;
	}
			
	var rot:Quaternion = Quaternion.FromToRotation(Vector3.up, hit.normal);
	transform.rotation = rot;
			
		}

Essentially no matter what I try, on the line where the transform.rotation gets set to rot, the Y-axis will either snap to 0, will bob violently or just will not work with some other undesirable result.

Some examples of what I tried are:

  • in getting the Quaternion, I changed Vector3.up to transform.up
  • in the line where I set the rotation to rot, I changed it to this transform.rotation *= rot
  • myriad of other random thing

Any help here would be greatly appreciated as I am real stuck here. Thanks in advance!

If you want to keep the object floating a fixed height over the terrain, try something like:-

transform.position = hit.point + transform.up * floatHeight;

Also, do this after you’ve set the rotation to the surface normal.

@andeeee - thank you for the reply. I made the change you suggested ( makes sense ). :slight_smile:

Unfortunately, the Y-axis is still forcing the Y-axis to 0 so the GO is going in a single direction. The updated code looks like this:

var fwd:Vector3 = transform.TransformDirection(Vector3.forward);
		
transform.position += fwd/speedModifier;
		
var hit:RaycastHit;
if (Physics.Raycast(transform.position, -transform.up, hit, 10)){

var rot:Quaternion = Quaternion.FromToRotation(Vector3.up, hit.normal);
transform.rotation = rot;
			
transform.position = hit.point + transform.up * .5;

I have attached a couple images for reference. Basically, the ant is rotated 180 on the Y-axis and the setting of the rotation to the FromToRotation is always forcing the Y-axis to 0. What I would like is that I can enforce the direction the ant is facing.

Any ideas, I am hoping someone can help because I am stuck and yanking out all the hair I have left. :-p

Thank you in advance.

236717--8468--$ant_start_rot_404.png
236717--8469--$ant_once_rot_applied_191.png