Quaternion.RotateTowards() rotates on multiple axis

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. :smile:
(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);           
        }


    }
}

If you’ve already rotated the turret base to face towards the target in every direction except vertical, then your simplest option is probably just to skip all the coordinate manipulation you’re trying to do and tell the cannons to look directly towards the target in every dimension. They’ll already have the correct horizontal rotation, so they should only change vertically.

If you don’t want to rely on that, then I believe you’re going to need to work in local coordinates instead of global coordinates; project the target point onto the vertical plane that the turret is already facing rather than the vertical plane that’s aligned with the global Y and Z axes. You can do that either by transforming all coordinates into the reference frame of the turret, or by calculating the appropriate plane and then projecting the global coordinates of the target onto the closest point of that plane.

Thank you, i did what you said in the first part of your message and that solved the problem.