- Home /
Limiting Local Turret Rotation
Hi guys
There are a few similar questions out there, but none of them seem to work in my case.
Basically, I have a turret on a vehicle that tracks a target. It will always rotate towards the target:
public int turretSpeed = 90;
void FixedUpdate () {
//if the vehicle has a target
if(gameObject.transform.parent.GetComponent<Unit>().target)
{
Quaternion facing = Quaternion.LookRotation(gameObject.transform.parent.GetComponent<Unit>().target.transform.position - transform.position);
transform.rotation = Quaternion.RotateTowards(transform.rotation, facing, turretSpeed * Time.fixedDeltaTime);
}
}
This works fine, but I'd like to make the turret unable to rotate more than 90 degrees on either side, but I've been unsuccessful thus far.
I tried placing this after the code:
Vector3 angle = transform.localEulerAngles;
angle.y = Mathf.Clamp(angle.y, -90.0f, 90.0f);
transform.localEulerAngles = angle;
But this proved unpredictable, and the turret would spin 360 degrees after the parent object moved.
Can anyone offer some advice?
I cannot fully visualize this problem. You have some sort of parent object. What kinds of rotations does it do and for what reason. Is it limited in any way. The script above goes on the child. I don't see any limits on the targeting code, so right now it can point this object in any direction to acquire the target. Does it point in arbitrary directions or is something limiting where it points.
Finally you talk about clamping the 'Y' rotation. What is the frame of reference for the angle? Are you 'just' clamping in relationship to the local forward?
Basically, it's a tank in an RTS. I tell the vehicle to move around, and it does (using A*). On top of it, I have the child gameobject with the turret script included above.
As the code appears in the top block, it has no limits. I right click on a target, and the turret tracks the target, no matter what. What I want is to say something like "The turret can't twist more than 90 degrees left or right, 40 degrees up, and 10 degrees down", for example.
The solution I attempted was to check each update if the turret was twisted more than 90 degrees in local space, and set it to 90 so that it doesn't go further, but it didn't work.
Sorry if my question was vague.
Your answer
Follow this Question
Related Questions
Limit local rotation 6 Answers
problems with quaternion rotations 4 Answers
Limit Object Angle 2 Answers