Turret rotation for a tank that can move over a terrain is complicated. Below is a script I wrote for another question, but the code was buried down some levels in comments, so I’ll repost it here. It has a restriction on the angle of the gun. This restriction is based on the starting angle of the gun.
This code is designed to be added to the turret. Then the guns (as child objects) would initialize the ‘gun’ transform.
I don’t know how you are handling your target, but in this script ‘target’ needs to be initialized.
#pragma strict
var target : Transform;
var gun : Transform;
var turretDegreesPerSecond : float = 45.0;
var gunDegreesPerSecond : float = 45.0;
var maxGunAngle = 45.0;
private var qTurret : Quaternion;
private var qGun : Quaternion;
private var qGunStart : Quaternion;
private var trans : Transform;
function Start() {
trans = transform;
qGunStart = gun.transform.localRotation;
}
function Update () {
var distanceToPlane = Vector3.Dot(trans.up, target.position - trans.position);
var planePoint = target.position - trans.up * distanceToPlane;
qTurret = Quaternion.LookRotation(planePoint - trans.position, transform.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTurret, turretDegreesPerSecond * Time.deltaTime);
var v3 = Vector3(0.0, distanceToPlane, (planePoint - transform.position).magnitude);
qGun = Quaternion.LookRotation(v3);
if (Quaternion.Angle(qGunStart, qGun) <= maxGunAngle)
gun.localRotation = Quaternion.RotateTowards(gun.localRotation, qGun, gunDegreesPerSecond * Time.deltaTime);
else
Debug.Log("Target beyond gun range");
}