Menu
CoddyTech

Euler Angles

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 42 of 71.

transform.eulerAngles is an object's rotation as three angles in degrees, around x, y and z. Unity stores the rotation as a quaternion (the next lesson) and works the three angles out again each time you read them, always as values from 0 up to 360. Tilt a plank to -10 degrees around z and read it back:

transform.rotation = Quaternion.Euler(0, 0, -10);
Debug.Log(transform.eulerAngles.z);   // 350

You set -10, but the code reads 350, so if (transform.eulerAngles.z < -5) is never true. Reading back can change all three numbers: set (100, 0, 0) and you read (80, 180, 180), the same orientation written another way. Quaternion.Euler(x, y, z) goes the other direction and accepts any angle: -10, 350 and 710 build the same rotation. So keep the angle in a float of your own, change and limit it there, and set the whole rotation from it. This seesaw tilts with the arrows and stops at 20 degrees either way:

public float speed = 40f;
float tilt;

void Update()
{
    tilt += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
    tilt = Mathf.Clamp(tilt, -20f, 20f);
    transform.rotation = Quaternion.Euler(0, 0, tilt);
}

Do not change one part of the angles you read. transform.eulerAngles.x = 110; does not compile (CS1612, as with position.x), and copying eulerAngles, changing x and assigning the copy back starts from Unity's version of the angles. After setting (100, 0, 0), that copy is (80, 180, 180); add 10 to x and you get (90, 180, 180), which turns the object back to 90 instead of on to 110.

challenge icon

Challenge

Medium

Fix the camera's sweep: it turns back at 45 but not at -45, because eulerAngles.y reads -45 as 315.

  1. Add a field float angle; and replace the two first lines of Update() with angle += direction * speed * Time.deltaTime;.
  2. Keep the two if lines, then set the whole rotation: transform.rotation = Quaternion.Euler(tilt, angle, 0);.

Press Play: the camera sweeps from 45 to -45 and back, tilted down. Then Check.

Try it yourself

using UnityEngine;

public class Sweep : MonoBehaviour
{
    public float speed = 30f;
    public float limit = 45f;
    public float tilt = 20f;   // degrees down, around x
    float direction = 1f;

    void Update()
    {
        transform.Rotate(0, direction * speed * Time.deltaTime, 0, Space.World);
        float angle = transform.eulerAngles.y;
        if (angle > limit) direction = -1f;
        if (angle < -limit) direction = 1f;
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground