Search code examples
c#unity-game-engine

Unity C# light angle does not change


I'm trying to create a game in which helicopter light follows a target. This is the code I'm trying to do it with:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class helicopterLight : MonoBehaviour
{
    public Transform target;
    public int MaxAngle = 30;

    void Update()
    {
        if (transform.localRotation.x < 90 + MaxAngle && transform.localRotation.x > 90 - MaxAngle)
        {
            transform.LookAt(target.position);
        }
    }
}

90 degrees is written in purpose, to make the light face down.


Solution

  • Rotation in Unity is always a Quaternion. This has more than 3 components but 4: x, y, z, w which all move in range -1 to 1.

    So this will never be anywhere near the range of 90°.

    If you want to limit the rotation it is easier to do so in Euler angle space (the ones you know). You could do so using e.g.

    Vector3 directionToTarget = target.position - transform.position;
    // Rotation that would be required to fully look at the target
    Quaternion lookRotation = Quaternion.LookRotation(directionToTarget);
    // Euler space representation of the quaternion
    Vector3 euler = lookRotation.eulerAngles;
    // manipulate and clamp according to your needs
    euler.x = Mathf.Clamp(euler.x, 90 - MaxAngle, 90 + MaxAngle);
    // apply
    transform.localRotation = Quaternion.Euler(euler);
    

    See


    Note that in general eulerAngles not always behaves as expected and seemingly the same looking Quaternion can have quite different Euler representations