I'm trying to enhance a simple clamp to terrain script I wrote to also rotate the object based on the angle of the terrain under it. There is probably easier ways to do what I am trying to do, but I'd also like to know why my code is simply not working.
function AlignToTerrainAngle(pos : Vector3, unitSize : float = 1.0) {
var frontSide : Vector3 = Vector3(pos.x + unitSize, 0, pos.z);
frontSide.y = terrain.SampleHeight(frontSide);
var backSide : Vector3 = Vector3(pos.x - unitSize, 0, pos.z);
backSide.y = terrain.SampleHeight(backSide);
var leftSide : Vector3 = Vector3(pos.x, 0, pos.z + unitSize);
leftSide.y = terrain.SampleHeight(leftSide);
var rightSide : Vector3 = Vector3(pos.x, 0, pos.z - unitSize);
rightSide.y = terrain.SampleHeight(rightSide);
// get pitch angle
var pitchAngle : float = Vector3.Angle(frontSide, backSide);
// get yaw angle
var yawAngle : float = Vector3.Angle(leftSide, rightSide);
Debug.Log("Pitch angle: " + pitchAngle + " Yaw angle: " + yawAngle);
var newRotation : Quaternion = Quaternion.identity;
newRotation += Quaternion.AngleAxis(pitchAngle, Vector3.right);
newRotation += Quaternion.AngleAxis(yawAngle, Vector3.forward);
// Rotate the model!
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 2.0);
}
I feel like I'm pretty close, but the angles are way too small (< 0.3), and assigning the new rotation Quaternion to the transform object seems to do nothing. Even hard coding larger angles resulted in no change.
Great, works perfect! Thanks a lot.
– RicaneThank you. Your answer probably causes butterfly effect and save the world from alien invasion.
– chanfui