- Home /
Rotate object to a specific angle and then stop.
I need to be able to define a rotation value in all three axis, have the object rotate to that point over a certain time period (which I also define in a variable), and then have it stop moving once it reaches that point (or gets within 1 or 2 units of the point).
How do I do this?, Transform.Rotate doesn't seem to let me specify a specific point to go to, and I have no idea how to use Quaternions.
Answer by cloudcamaleoniv · Aug 13, 2014 at 06:13 PM
So, you want to animate the rotation value over time until it reaches a certain value.
Inside the Update method, you can use the Lerp method to keep rotating the object to a point, but you will never really reach this point if you use Lerp. It will keep rotating forever (always closer to the point).
You can use the following:
private bool rotating = true;
public void Update()
{
if (rotating)
{
Vector3 to = new Vector3(20, 20, 20);
if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
{
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);
}
else
{
transform.eulerAngles = to;
rotating = false;
}
}
}
So, if the distance between the current object angle and the desired angle is greater than 0.01f, it jumps right to the desired position and stop executing the Lerp method.
Answer by admin_8C · Jun 13, 2017 at 08:56 AM
I turn again and again..... never stop... doesnt works
This works for me... I hope it helps you:
void Update (){ if (rb.transform.rotation.z != (out2 )) StartCoroutine (RotateZell ());
}
IEnumerator RotateZell () { while(rb.transform.rotation.z < out2 || rb.transform.rotation.z > out2) { rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, Quaternion.Euler(0, 0, out2), 0.1f * Time.time); yield return null; }
rb.transform.rotation = Quaternion.Euler(0, 0, out2);
yield return null;
}