Little math problem with rotation :)

Ok, this might be a fundamental math problem, but I’m not getting it, maybe I need a little tip. ;D

So, I have a unit (top-down-view), which is rotated at 0° when looking up (north), 90° when looking east, 180° south, 270° west and there is no 360°, it goes back to 0°.

Let’s imagine the unit is looking east (90°), and I received a new rotation that the unit needs to smoothly transition to, let’s say this is 340°.

Now I need to figure out if I need to rotate the unit clockwise or counter-clockwise. In this case I need to rotate counter-clockwise since it’s the shortest distance to the new angle (I only need to rotate 110° instead of 250° if I would rotate clockwise!).

How would you do this?

Nm, MatthiasM worked it out for me :slight_smile:

Here’s the code I implemented.

rotation = the current rotation
directionAngle = the rotation I want to be at!


	private void updateRotation(int delta) {
		float previous = rotation;

		// next two lines important! x is negative on CCW, but positive on CW!
		float x = (((directionAngle-rotation)%360)+360)%360;
		if(x > 180) x -= 360;
		
		if(x > 0) {
			rotation = (rotation+((float)delta*DEFAULT_ROTATION_SPEED));
			if(rotation > directionAngle && previous < directionAngle)
				rotation = directionAngle;
			rotation = rotation%360;
		} else {
			rotation = (rotation-((float)delta*DEFAULT_ROTATION_SPEED));
			if(rotation < directionAngle && previous > directionAngle)
				rotation = directionAngle;
			rotation = rotation%360;
		}
		
	}

if(new > 360 || new < 1) throw illegalArgumentException("not a legal value for … ");
return (new>old) ? (old-new) > 180 : !((new-old) > 180);

returns true if clockwise false otherwise.

I should write a unittest for it and check if it actually works, I’m too tired now. tbh considering how sleepy I am it might be bullshit altogether.