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.
1
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
Quaternion.LookRotation
Quaternion.eulerAngles
Quaternion.Euler
Note that in general eulerAngles
not always behaves as expected and seemingly the same looking Quaternion
can have quite different Euler representations
The problem is euler angles here. Try out this code:
void Update()
{
Vector3 directionToTarget = target.position - transform.position;
float angleToTarget = Vector3.Angle(Vector3.down, directionToTarget);
if (angleToTarget < MaxAngle)
{
transform.LookAt(target.position);
}
}
}
1