- Home /
What causes this object to re-rotate itself after it hits it's destination?
As seen here:
I'm using the following code to rotate the object:
private void RotateToDestiantion()
{
Vector3 lookPos = destination - transform.position;
float angle = (Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg) - 90;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * 2f);
}
Destination is a vector 3 where the mouse clicks. I have to subtract 90 degrees off the angle so it actually faces the mouse and is not -90 degrees off. I have absolutely no clue what causes it to rotate after it reaches it's destination.
Answer by douglasg14b · Feb 07, 2015 at 06:24 PM
So I think I may have figured this out.
When I determine the angle:
Vector3 lookPos = destination - transform.position;
float angle = (Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg) - 90;
I need to do this outside of the function that is in Update(). When the ship stops moving the angle field resets back to 0 degrees (in this case -90 degrees since I subtract 90 from the angle). This happens because the destination and the transform.position are the same, which results in the lookPos being 0. This is resolved by moving the angle determination outside of the looping method.
Additionally, to stop the rotation anyways, I made a check that switches a bool to stop the rotation if it is within a certain allowable distance. I am only pasting this in here for future reference for anyone else that searches for and comes across this post.
if (angle < 0)
{
float checkAngle = 360 + angle;
if (checkAngle < (transform.rotation.eulerAngles.z + 0.5f) && checkAngle > (transform.rotation.eulerAngles.z - 0.5f))
{
rotating = false;
}
}
else if (angle > 0)
{
float checkAngle = angle;
if (checkAngle < (transform.rotation.eulerAngles.z + 0.5f) && checkAngle > (transform.rotation.eulerAngles.z - 0.5f))
{
rotating = false;
}
}