- Home /
lerp between two xyz rotation values
Hi there
Apologies for the noobiness of this question,
I want to create a lerp ( or even better a smoothstep) between two rotation values. My code below creates a very sudden transition over one frame. Duration is a float with val 20f
many thanks in advance!
void Update () {
if (armstate == 1) {
transform.eulerAngles = Vector3.Lerp (startRot,endRot,duration);
armstate = 0;
}
if (armstate == 2) {
transform.eulerAngles = Vector3.Lerp (endRot,startRot,duration);
armstate = 0;
}
Answer by robertbu · Apr 04, 2013 at 04:43 AM
The final parameter of the Lerp() is a value between 0 and 1 inclusive. A standard way of using Lerp() is to create a timer and use the timer in the final parameter calculation. Here is your code with some changes. It probably doesn't do want you want, but it does show Lerp() in action. Attach this script to a Cube object and hit play.
using UnityEngine;
using System.Collections;
public class LerpDemo : MonoBehaviour {
Vector3 startRot = new Vector3(-30.0f,-30.0f,-30.0f);
Vector3 endRot = new Vector3(60.0f, 60.0f, 60.0f);
int armstate = 0;
float duration = 20.0f;
float timer = 0.0f;
void Update () {
timer += Time.deltaTime;
if (timer > duration) {
armstate = (armstate + 1) % 2;
timer = 0.0f;
}
if (armstate == 0) {
transform.eulerAngles = Vector3.Lerp (startRot,endRot,timer/duration);
}
if (armstate == 1) {
transform.eulerAngles = Vector3.Lerp (endRot,startRot,timer/duration);
}
}
}
thanks that was very helpful! starting to get my head around it now!
This class is great but I would make one change. Eulers are awful at lerp-ing since order of operation matters, ie, xyz, yzx, zxy, etc. The rotation can often look really strange. Gimble lock can happen too. Eulers work fine for a while, then at certain angles it will spaze. You can keep your rotations in euler but lerp them in Quaterion.
So
Vector3 startRot = new Vector3(-30.0f,-30.0f,-30.0f);
Becomes
Quaternion startRot = Quaternion.Euler( new Vector3(-30.0f,-30.0f,-30.0f) );
And
transform.eulerAngles = Vector3.Lerp (startRot,endRot,timer/duration);
Becomes
transform.rotation = Quaternion.Lerp(startRot,endRot,timer/duration);
Its really the same idea, but this will lerp in a mathematical space that is much more reliable.
Answer by jamesflowerdew · Jan 22, 2016 at 05:29 PM
to lerp from grot to a target angle named vRot::
gRot = new Vector3(Mathf.LerpAngle(gRot.x,vRot.x,pFrame),Mathf.LerpAngle(gRot.y,vRot.y,pFrame),Mathf.LerpAngle(gRot.z,vRot.z,pFrame));
works for me :)
It should be simpler (and less error-prone) to just use quaternions though:
gRot = Quaternion.Lerp(Quaternion.Euler(gRot), Quaternion.Euler(vRot)).eulerAngles;
Your answer
Follow this Question
Related Questions
How to smoothly rotate to certain directions using input axis 1 Answer
Issues with Lerps 2 Answers
Lerping euler angles make entire spin 3 Answers
How to know if a gameobject is rotating? 1 Answer
How would I smooth out a Quaternion? 2 Answers