Clamped Turret Doesn't Want to Lerp the Other Way

I have a clamped turret that tracks and works fine. However, when it is tracking one direction and has hit its max rotation and the target “flips” to other side, the turret doesn’t want to rotate the other way to get to the target. Instead it is trying to rotate the shortest path but can’t because it is clamped. I wasn’t sure how to explain it, so I fired up MS Paint before MS kills it and made a quick and dirty picture explaining it:

135850-rotationexample.png
Below is part of the script that manages the yaw:

relativePosition = yawSegment.InverseTransformPoint(targetTransform.position);
angle = Mathf.Atan2(relativePosition.x, relativePosition.z) * Mathf.Rad2Deg;

targetRotation = yawSegment.rotation * Quaternion.Euler(0f, Mathf.Clamp(angle, -yawSpeed * Time.deltaTime, yawSpeed * Time.deltaTime), 0f);

yawSegment.rotation = Quaternion.RotateTowards(yawSegment.parent.rotation * yawSegmentStartRotation, targetRotation, yawLimit);

Does anyone have a simple solution to this? I am open to changing how the turret rotates. Thanks in advance!

https://forum.unity.com/threads/left-right-test-function.31420/


Check the target position relative to your turret. The simplest is to check left or right. If its on the right side, rotate CCW towards the target, if its on the left rotate CW. Then you check if the turret is pointing left or right, and handle the rotation accordingly. Because if the target is left, and the turret is pointing upper-left, you don’t want it to rotate CW. So you need something like a check to see where the turret is. If opposite side: rotate towards right side. If right side, use tracking system. As you might notice this is very basic. You can expand this by creating 4 quadrants by checking up and down to. Not saying this is THE way to go, but it is A way to go and might push you towards a solution. Good luck.

How would I smoothly rotate CW or CCW and then land on a target? I tried looking at relative position but then I struggled to get the turret to point correctly at the target.