# Rotation upside down problem.

I have a patrolling 2D object that I want to look at the target it’s moving towards. The problem is sometimes the object turns upside down, when the Z rotation has a high number.

``````Vector3 dir = target.position - transform.position;
float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;

Quaternionq = Quaternion.AngleAxis(angle,  Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation,q,Time.deltaTime*speed);
``````

Well, first, I notice you’re abusing Lerp, and should probably be using Quaternion.MoveTowards instead. But since it’s a 2D game, you could instead just keep track of your current angle (or read it out of transform.eulerAngles.z), and use Mathf.MoveTowardsAngle with this angle.

So I certainly recommend that change, but I don’t think it’s the problem you’re asking about. It sounds like sometimes your object turns upside down while tracking the target. But isn’t that what would you expect? What do you want it to do instead, when the target is in a direction that requires it to be upside down in order to face it?

(Perhaps a picture would help us to understand the problem.)

1 Like

It happens I guess when the target is not in the “Forward” direction of the object, then I think it should flip instead of rotating upside down, meaning it’s X scale should be -1, but I’m not totally sure.

OK, so I think I see what you want. If the angle is in (say) the range -90 to +90, you want to just point towards the target. But if it’s outside that range, then you want to flip, and appear to point towards the target.

That’s a little tricky! But doable. And you’ve already done the first step, which is calculating the angle.

So, why don’t you Debug.Log that angle, so you’re sure you know what values you’re getting, and then play around with some logic setting the scale according to the desired angle.

I recommend you do this first without worrying about interpolation (i.e., take out the MoveTowards or Lerp calls). Then, once you have it turning instantly the way you want, you can extend it a little more to interpolate.