If angle is greater than 5, do something, if less than -5, do something else [Answered]

Hello!

I’m currently making a (loosely) physics based top-down car game that works pretty well so far.

One thing that I do have a problem though, is that when you steer either left or right, your car either rotates left or right, simulating car suspension.

Now, I’ve quickly created a little piece of code that doesn’t work at all, and I’m not completely sure why (it’s nearly 2am here so I am quite tired)

It’s this:

		if ((Input.GetKey ("a")) & Car.rotation.eulerAngles.z <= -5){
			RigidCar.AddTorque(Car.forward * -100);
		}

		if ((Input.GetKey ("d")) & Car.rotation.eulerAngles.z >= 5){
			RigidCar.AddTorque(Car.forward * 100);
		}

I’d like all the help I can receive! Thanks!

I feel you. I had this issue a few days ago.

Unity’s “eulerAngles” tends to use positive angles more often than not, so when you’re doing -5º, the engine is actually working with 355º. Because you compare them with regular >, < or == operators, they get compared as mere numbers, not angles.

I made a fast, recursive function to solve this problem. It’s static, so you can put it in a “Utility.cs” script with a static class, so you can use it anywhere in your program (ie: Utility.ToEulerAngles(Car.rotation.eulerAngles.z);):

	/**
	 * Returns a number expressed as euler angles with +-180 notation:
	 * 
	 * 500 -> 140
	 * 450 -> 90
	 * 270 -> -90
	 * 0 -> 0
	 * 180 -> 180
	 * -180 -> 180
	 */
	public static float ToEulerAngles(float number) {
		// POSITIVE NUMBERS
		if (number >= 0) {
			// [0, 180] -> Return number
			if (number >= 0 && number <= 180) {
				return number;
			} 

			// (180, 360] -> Return number - 360
			else if (number > 180 && number <= 360) {
				return number - 360;
			} 

			// (360, inf) -> Recursive calculation with number % 360
			else { /* if (number > 360) */
				return ToEulerAngles (number % 360);
			}
		}

		// NEGATIVE NUMBERS
		else {
			// (0, -180) -> Return number
			if (number < 0 && number >= -180) {
				return number;
			}

			// -180 -> 180
			else if (number == -180) {
				return 180;
			}

			// (180, 360] -> Return number + 360
			else if (number < -180 && number >= -360) {
				return number + 360;
			}

			// (-inf, -360) -> Recursive calculation with number % 360
			else { /* if (number < 360) */
				return ToEulerAngles (number % 360);
			}
		}
	}

Hope it helps!

Or just…

Mathf.Repeat(n + 180, 360) - 180