Hello. I am working on making a transform stay above the terrain, this means it should basically “hug” it and always be x amount of meters above it and rotate accordingly. The staying above I got working. The rotating too. Except for one odd thing.
I use the normals to rotate the transform, however, this only works into positive z. It won’t work into negative z: The transform is facing negative z but the rotation is still positive z. Now, I could just flip the rotation around on the z axis, but this won’t work as I don’t have z rotation at either 0 or 360 since the transform can move freely in space.
This is my code:
RaycastHit hit;
if (Physics.Raycast(transform.position, -curNormal, out hit)){
// curNormal smoothly follow the terrain normal:
curNormal = Vector3.Lerp(curNormal, hit.normal, 4*Time.deltaTime);
// calculate rotation to follow curNormal:
Quaternion rot = Quaternion.FromToRotation(Vector3.up, curNormal);
// rotate apply rotation to transform except for Y
transform.rotation = new Quaternion(0, transform.rotation.y, 0, transform.rotation.w) * rot * iniRot;
}
iniRot is just a Quaternion of the rotation at the beginning (essentially 0,0,0)
To clarify:
Here it is facing positive z. Works: http://snag.gy/ZhAoB.jpg
Here it is facing negative z. Doesn’t work: http://snag.gy/SvknB.jpg