Hello,
I’m trying to code a turret that can follow a target the turret need to rotate only on the y axis and the cannons need to rotate only on the x axis.
The following code works for the turret but when i’m trying to do the same with the cannons, it also rotate on the y axis with the same angle from the turret rotation (the x axis rotation is correct).
I don’t really understand it behaves like that
It works fine if i use eulerAngles but i want the smooth tracking of a target.
here’s my code and a video if someone can help me. ![]()
(I rotate the canons after only for better visualization)
public class Turret : MonoBehaviour
{
public float turnSpeed = 20;
public GameObject turretAxe;
public GameObject cannon1;
public GameObject cannon2;
GameObject target;
private void Start()
{
target = GameObject.FindGameObjectWithTag("Target");
}
private void Update()
{
Vector3 direction = new Vector3(target.transform.position.x,turretAxe.transform.position.y, target.transform.position.z) - turretAxe.transform.position;
Quaternion to = Quaternion.LookRotation(direction, Vector3.up);
turretAxe.transform.rotation = Quaternion.RotateTowards(turretAxe.transform.rotation, to, turnSpeed * Time.deltaTime);
if (turretAxe.transform.rotation == to)
{
direction = new Vector3(cannon1.transform.position.x, target.transform.position.y, target.transform.position.z) - cannon1.transform.position;
to = Quaternion.LookRotation(direction, Vector3.up);
cannon1.transform.rotation = Quaternion.RotateTowards(cannon1.transform.rotation, to, turnSpeed * Time.deltaTime);
cannon2.transform.rotation = Quaternion.RotateTowards(cannon2.transform.rotation, to, turnSpeed * Time.deltaTime);
}
}
}