How do I aim a tank turret at a point?
I have a tank model that can move and rotate freely on every axis. On top of it, there is a turret, which should only be able to rotate along the local Y axis, and a gun barrel connected to the turret which should only be able to pivot up and down. I want to be able to aim the gun at any point without violating these constraints, but nothing I've tried so far has worked. I guess I just don't understand quaternions :)
So can anyone give me any pointers on how to do this? I'm pretty lost.
Edit: Through trial and error, I got something that almost works. It works perfectly for any target that is approximately in front of the tank, but when the turret has to rotate a significant amount around the y axis, the gun no longer is at the right angle. I suspect this has something to do with gimbal lock but I'm not sure how to fix it.
Here's my code:
void FixedUpdate() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.DrawLine(hit.point, Camera.main.transform.position, Color.red);
Quaternion dir = Quaternion.LookRotation(gun.transform.position - hit.point, Vector3.up) * Quaternion.Euler(90, 0, 0);
Vector3 localDir = (Quaternion.Inverse(transform.rotation) * dir).eulerAngles;
turret.transform.localRotation = Quaternion.AngleAxis(-localDir.z, new Vector3(0, 0, 1));
gun.transform.localRotation = Quaternion.AngleAxis(-localDir.x, Vector3.right);
Debug.DrawLine(hit.point, gun.transform.position, Color.green);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612084102im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Keep object within circle on plane 0 Answers
How do I find a point along a line with a forced x and z values 0 Answers
Goldeneye / Perfect Dark aim assist 0 Answers
Making 2D Compass From Quaternion 1 Answer