- Home /
Rotating an Object in Update Function
I originally was using: transform.Rotate But it rotated the object...forever. I want to rotate my object 90 degrees left and then STOP the rotation. But transform.Rotate just continued it because it was in an Update function. How can I stop the rotation at 90 degrees. Do I need to use a Quaternion? I've tried learning about Quaternions on Unity Scripting API but can't seem to get my head around them - they seem more complicated than what I want to do. Anyway, thank you if you know the answer to this!
http://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html
from = current rotation (transform.rotation)
to = desired
http://docs.unity3d.com/ScriptReference/Quaternion.Euler.html
Quaternion desiredRotation = Quaternion.Euler(new Vector3(transform.eulerAngles.x, transform.eulerAngles.y + 90, transform.eulerAngles.z);
transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotation, overTime);
http://www.blueraja.com/blog/404/how-to-use-unity-3ds-linear-interpolation-vector3-lerp-correctly
Answer by Scribe · Nov 16, 2014 at 02:25 PM
How about using a coroutine, this is a rotate around method that will stop after the given number of degrees has been achieved:
bool isRotating = false;
public Vector3 this_Axis;
public float deg;
public float time;
void Update () {
if(Input.GetKey(KeyCode.Q) && !isRotating){
StartCoroutine(RotateAround(this_Axis, deg, time));
}
}
IEnumerator RotateAround(Vector3 axis, float degrees, float duration){
if(axis == Vector3.zero || degrees == 0){
return true;
}
isRotating = true;
float d = 0;
Quaternion q;
Quaternion startRot = transform.rotation;
float progress = 0;
while(progress <= 1){
d = Mathf.Lerp(0, degrees, progress);
q = Quaternion.AngleAxis(d, axis);
transform.rotation = startRot*q;
progress += Time.deltaTime/duration;
yield return null;
}
transform.rotation = startRot*Quaternion.AngleAxis(degrees, axis);
isRotating = false;
}
Hope that helps!
Scribe
Thank you! But agob1gry4n did seem to give a much simpler answer but I'll definitely give coroutine's a go!
It is simpler, I can't check at the moment but I think the difference is ig you want to rotate 360 degrees around an axis, this method will do the rotation where as lerp will think the start and end rotations are the same and therefore won't rotate! But that might be desired behaviour :) thanks for marking as answered
Your answer
Follow this Question
Related Questions
Adding quaternions using a seperate axis 0 Answers
Aiming to gameobject 2 Answers
How to use a negative value when MathF.Clamping a eulerAngle? 1 Answer
transform.forward wobbles about instead of rolling 1 Answer
Rotate Issue 0 Answers