- Home /
Clamping LookRotation angle
I have a turret that aims up and rotates on the Z-axis, using LookRotation to look at specific game objects. I tried to use my eulerAngles clamp that works for my player controlled turret that rotates on the same axis with mouse input using transform.Rotate. Here is the script:
Vector3 look = target.transform.position - transform.position;
look.z = 0;
targetRotation = Quaternion.LookRotation (look);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
transform.eulerAngles = new Vector3(0, 0, Mathf.Clamp (transform.eulerAngles.z, CminAngle, CmaxAngle));
The Mathf.Clamp line just causes the turret to turn sideways and stay that way. Is clamping LookRotation not the same as clamping transform.Rotate?
Answer by robertbu · Aug 21, 2013 at 10:49 PM
Any eulerAngle you get is converted from a Quaternion. Any angle you set is converted to a Quaternion. The angle you set is not necessarily the same one you get back. For example execute this code:
transform.eulerAngles = new Vector3(180,0,0);
Debug.Log(transform.eulerAngles);
The value you will get back is (0,180,180), the same physical rotation, but a different Euler angle representation. So clamping your Euler angles will not work all the time. One way to fix your code is to instead test the angle of two Quaternions. Assuming your turret is pointed half way between the two max angles on start, you can do this (untested):
using UnityEngine;
using System.Collections;
public class Tracker : MonoBehaviour {
public Transform target;
public float maxAngle = 35.0f;
private Quaternion baseRotation;
private Quaternion targetRotation;
void Start() {
baseRotation = transform.rotation;
}
void Update() {
Vector3 look = target.transform.position - transform.position;
look.z = 0;
Quaternion q = Quaternion.LookRotation (look);
if (Quaternion.Angle (q, baseRotation) <= maxAngle)
targetRotation = q;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
}
}
That seems to limit rotation to just one half of the turrets angle and also seems to make its movement a bit jittery and less smooth.
I changed the code a bit. The maxAngle represents the maximum degrees from the base angle allowed. The old code would stop tracking immediately when the target left the field of view. This new code will continue to the limit. This means that if the enemy comes back from the same side, this code will pick them up sooner.
That seems to work. But the best results are when I set the $$anonymous$$axRotation to 180. Does that mean the script is telling the turret it's allowed to rotate 180 degrees from the baseRotation?
Yes. Setting it to 180 will allow the turret a full 360 degrees of rotation.
Answer by drudiverse · Apr 06, 2014 at 04:54 AM
You can use Vector3.Angle as well to monitor deviation from wished direction.
if(vector3.Angle(centrallook.vector,currentlook.vector)<45){rotate towards....);