I have a turret (that’s a child of a robot gameobject) that rotates to track a target transform in global space along the y axis, that code works fine, but i now want to constrain the turret’s rotation between two angle values (e.g. -90, 90). I know I can use Mathf.Clamp(angle, -90, 90)
to clamp the turret angle on the y axis, but that only works globally (clamping to 0 keeps the turret at the global 0 angle not relative to the parent). I want the turret to still track the target properly but also be clamped between the min/max angle limits locally. Also something to note is that the turret’s scene rotation makes it rotate locally on the x axis but on the y axis globally to move the same way.
Heres my current turret movement code:
private void RotateTurret()
{
Vector3 targetDirection = target.position - turret.transform.position;
float turretAngle;
if (reverseTurret)
{
turretAngle = Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
}
else
{
turretAngle = Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg + 180f;
}
float turretRotationAmount = turretSpeed * Time.deltaTime;
Quaternion currentRotation = turret.transform.rotation;
Quaternion targetTurretRotation = Quaternion.Euler(0f, turretAngle, 0f);
turret.transform.rotation = Quaternion.RotateTowards(currentRotation, targetTurretRotation, turretRotationAmount);
}
As stated above I tried using the following code to clamp the angle, but it only did it in global space not relative to the parents rotation.
float clampedAngle = Mathf.Clamp(turretAngle, minTurretAngle, maxTurretAngle);
targetTurretRotation = Quaternion.Euler(0f, clampedAngle, 0f);
I also tried converting all the turret movement into using localRotation
, but then when the parent robot gameobject would rotate the turret would lose where it thought the target’s position was.
Any insights on how to possibly fix this issue would be greatly appreciated!