- Home /
Problem at 180 degrees when rotating slowly
I want the missile to turn slowly to the target, if the target is at the right side it works well, but when the target passes over it or is on the left side, to follow it the missile turns all the opposite way around. Here is the code:
void FixedUpdate () {
Vector3 dir = trans.position - transform.position;
float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
lastangle = Mathf.Lerp (lastangle, angle, rotationspeed); //looks like the problem appears if its not set instantly
transform.rotation = Quaternion.AngleAxis (lastangle, Vector3.forward);
rigidbody2D.velocity = new Vector2(transform.right.x*speed, transform.right.y*speed); //movement of the missile
}
It works correctly if the direction is instantly set to the target instead of using lerp.
I used the code from this answer http://answers.unity3d.com/questions/640736/creating-a-homing-missile-on-2d-problem-with-trans.html
Answer by Aridez · Feb 16, 2014 at 08:33 PM
Already solved it! Used the Quaternion.Slerp function:
void FixedUpdate () {
Quaternion from = transform.rotation;
/**/Vector3 dir = trans.position - transform.position;
/**/float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion to = Quaternion.AngleAxis (angle, Vector3.forward);
transform.rotation = Quaternion.Slerp (from, to, rotationspeed);
}
Your answer
Follow this Question
Related Questions
Creating a homing missile on 2D, problem with transform.lookat() 1 Answer
Homing missile not working. 1 Answer
2D head breaks when flipping character 0 Answers
Homing missile and LookAt issue 1 Answer