[2D] Rotating object to look at mouse, problems near 0 degrees.

Hello! I have looked around here for answers on how to write this script. I am a super-novice programmer with a little knowledge but almost none experience, especially on C# (Not even 24h into the language…)

Anyways, here is my problem:

I have a script that sucesfully makes an object instantly look to any direction using transform.rotation, but then I tried to adapt to give a rotation speed so it didn’t instantly look, and it worked, for a bit.

It uses an error system, desired angle - current angle. If the current angle is 20 and it wants to look to 40, error is 20, so it moves 20 degrees up at a limited speed of 4 degrees per frame. If the error happens to be negative, an if sets the speed to be negative so it reaches the point. My problem happens when there is the “jump” between 0 and 359.99…, for example if the desired angle is 20 and the current is 350, it calculates the error as -330 and turns all the way left instead of crossing the 0.

I managed to come up with this super arbitrary fix but it causes some really unwanted snapping near 0 degrees:

float TurretTurnSpeed = TurretSpeed;
		float mousePosx = Input.mousePosition.x;
		float mousePosy = Input.mousePosition.y;
		Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
		mousePosx = mousePosx - objectPos.x;
		mousePosy = mousePosy - objectPos.y;
		float desiredangle = Mathf.Atan2 (mousePosy, mousePosx) * Mathf.Rad2Deg;
		float error = 0;
		
		if (mousePosy > 0) {
						error = desiredangle - transform.rotation.eulerAngles.z;
				} else {
			            error = desiredangle - transform.rotation.eulerAngles.z + 360;
				}
		
		if (Mathf.Abs (error) < 10) {
			TurretTurnSpeed = TurretSpeed / 5;
		}

		if (Mathf.Abs (error) > accuracy) {
			if (error < 0 && error > -180) {
				transform.Rotate(Vector3.forward, -TurretTurnSpeed);
			} else {
				if (error > 180) {
				transform.Rotate(Vector3.forward, -TurretTurnSpeed);
				} else { 
					transform.Rotate(Vector3.forward, TurretTurnSpeed);
				}
			}
		}

I think I can manipulate the error to fix this in a smoother way. Meanwhile I post this here to ask if there is a better way to solve my problem or a workaround method that doesn’t even have it.

If I was writing an smoothed, eased rotation for 2D, I would might do:

public float speed = 6.0f;
 
void Update () {
    Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
    Vector3 dir = Input.mousePosition - pos;
    float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward); 
    transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}

If you want a smoothed but not eased rotation, then replace ‘Slerp’ with ‘RotateTowards’ and greatly increase the value of ‘speed’. Note this code assumes the front of the object is facing right when the rotation is (0,0,0).