Euler Angles
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 40 of 63.
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); // 350You 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
MediumThe security camera on the pole should sweep from side to side for good: from facing ahead (0 degrees around y) it turns right, y growing, at speed (30) degrees per second, turns back at limit (45), sweeps across to -limit (-45), turns back again, and so on. The whole time it keeps its downward tilt of tilt (20) degrees around x.
Press Play: the starter turns back at 45, but at -45 it carries on round. Find out why and fix the script, then press 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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall