I got a strange result with the following code:
public Transform obj;
Vector3 result;
Vector2 targetAngle;
targetAngle = [...some calculations...]
result = obj.localEulerAngles;
result.x = Mathf.Lerp(obj.localEulerAngles.x, targetAngle.x, Time.deltaTime)%360;
result.y = Mathf.Lerp(obj.localEulerAngles.y, targetAngle.y, Time.deltaTime)%360;
obj.localEulerAngles = result;
Debug.Log(result+" <> "+obj.localEulerAngles);
Here is the result:
(90.4, 179.9, 0.0) <> (90.0, 179.9, 0.0)
(91.3, 179.5, 0.0) <> (90.0, 179.5, 0.0)
(91.0, 179.2, 0.0) <> (90.0, 179.2, 0.0)
Values are shown immediately after EulerAngles is changed, I dont know why EulerAngles.x remains unchanged, any ideas? Thanks.
Despite the docs call eulerAngles a variable, it’s actually a completely virtual property: it’s just transform.rotation converted from/to the 3 axes representation by internal getter/setter routines on the fly. Due to this, the sequence read/modify/write is a recipe for disaster for eulerAngles: the precision errors occurred during the conversion from/to quaternion accumulate each cycle, and the object may get tilted at weird angles after some time.
To avoid this problem, save the initial localEulerAngles in a Vector3 variable and Lerp this variable to targetAngle, assigning it to transform.localEulerAngles each cycle:
Vector3 curEuler;
void Start(){
curEuler = transform.localEulerAngles;
}
// in the loop:
targetAngle = [...some calculations...]
// you may use Vector3.Lerp directly:
curEuler = Vector3.Lerp(curEuler, targetAngle, Time.deltaTime);
obj.localEulerAngles = curEuler; // assign the lerp'ed value each cycle
NOTE: Notice that I replaced the two Mathf.Lerp with a single Vector3.Lerp, and ignored the modulo 360. The Lerp replacement is just a suggestion (maybe C# asks for a Vector3 typecast in front of targetAngle), but the modulo 360 removal isn’t: you can’t apply modulo 360 in this particular usage of Lerp (which I call lerp filter) because it’s a non-linear transformation and will produce weird results when getting out of the range 0…360 - if you want to limit the excursion, apply the modulo to the targetAngle components.