- Home /
Simple lerp roation problem
For a game i am making i need the character to be able to turn on the y axis to point forward, right, backward, and left. To do this i am using Mathf.Lerp with if statements to allow me to change the direction to these simple four directions. whenever i do this though, the characted will only point forward (0 degrees)or backward (180 degrees), can someone tell me where I went wrong, here is the script.
#pragma strict
function Start () {
}
function Update () {
if(Input.GetKeyUp(KeyCode.UpArrow)){
transform.rotation.y=Mathf.Lerp(transform.rotation.y,0,Time.time);
};//endif
if(Input.GetKeyUp(KeyCode.RightArrow)){
transform.rotation.y=Mathf.Lerp(transform.rotation.y,90,Time.time);
};//endif
if(Input.GetKeyUp(KeyCode.DownArrow)){
transform.rotation.y=Mathf.Lerp(transform.rotation.y,180,Time.time);
};//endif
if(Input.GetKeyUp(KeyCode.LeftArrow)){
transform.rotation.y=Mathf.Lerp(transform.rotation.y,270,Time.time);
};//endif }
Answer by aldonaletto · May 27, 2012 at 06:04 AM
This is a recurrent problem: transform.rotation is a quaternion, and you should not change its components directly unless you know exactly what you're doing. You should use transform.eulerAngles instead: this property is what you can see in the Rotation field, in the Inspector.
But there's another problem: with this Lerp code, the object will always rotate instantaneously to the target angle (the Lerp example in the docs sucks!)
To solve both problems, you could have two variables: curAngle and destAngle; each Update, curAngle Lerp's to destAngle, and is copied to the object rotation; when a key is pressed, set the destAngle:
private var curAngle: float; private var destAngle: float = 0;
function Update () { if(Input.GetKeyUp(KeyCode.UpArrow)){ destAngle = 0;
} if(Input.GetKeyUp(KeyCode.RightArrow)){ destAngle = 90; } if(Input.GetKeyUp(KeyCode.DownArrow)){ destAngle = 180; } if(Input.GetKeyUp(KeyCode.LeftArrow)){ destAngle = 270; } // choose the shortest distance: var dif = destAngle - curAngle; if (dif > 180) curAngle += 360; if (dif < -180) curAngle -= 360; // lerp curAngle to the destAngle each Update: curAngle = Mathf.Lerp(curAngle, destAngle, Time.deltaTime); // copy curAngle to the object Y angle: transform.eulerAngles = Vector3(0, curAngle, 0); }