Turret rotation angle

Let’s say I have a turret and a target like the ones shown bellow. How do I calculate rotation angle I need to rotate the turret around y axis for it to start hitting the target and the angle at which it becomes rotated too much and stops hitting the target. Keep in mind that the cannon is not placed in the center of the turret.
Turret

1 Answer

1

Ok typically if the cannon was in line with the pivot point of the turret you could use The Quaternion.LookAt function to determine the desired Rotation. However, with this offset turret you are going to need to add an additional offset angle. The magnitude of this angle is going to depend on both how far way the target is from the pivot point and how far offset the turret is from the pivot(measured along an axis perpendicular to direction the turret is pointing). Anyway if you divide the turret offset by the distance you will get the tangent of the angle you need. You can use this to calculate the additional rotation to add. An example:

public class LookAt : MonoBehaviour 

{

public Transform target;
	public float offSetAngle;
	float turretOffset = 2.66f;//distance to barrel along x axis

void Update()
{
	Vector3 toTarget = target.position - transform.position;
	offSetAngle = Mathf.Atan(turretOffset / toTarget.magnitude) * Mathf.Rad2Deg;
	transform.rotation = Quaternion.LookRotation(toTarget)
			* Quaternion.AngleAxis(-offSetAngle , Vector3.up);
	
}

}

I'm not sure if this is the best solution to this problem and I'm interested in seeing other solutions if anyone has them.

Assuming that the target is or can roughly be approximated as a sphere or circle you can compute two offset angles where you add or subtract the targets radius to the turretOffset. offsetAngle1 = Mathf.Atan((turretOffset - radius) / toTarget.magnitude) * Mathf.Rad2Deg; offsetAngle2 = Mathf.Atan((turretOffset + radius)/ toTarget.magnitude) * Mathf.Rad2Deg; one of these will be minimum one will be max depending on your orientation.

I've found that my solutions lose accuracy as the target gets too close to the turret so I am still curious if anyone knows of a solution that doesn't require trig functions