the rotation of the gun in the tank does not work well

I wrote a script so that my cannon rotates in x, but when I rotate the turret, the cannon rotates in the opposite direction why so?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class mehanic : MonoBehaviour
{
    public Transform detail1;
   

    void Start()
    {
       


    }
    void FixedUpdate()
    {

        if (Input.GetKey(KeyCode.E))
        {
           

            detail1.rotation = Quaternion.RotateTowards(detail1.rotation, Quaternion.Euler(new Vector3(30, 0, 0)), 30f * Time.deltaTime);


        }
        if (Input.GetKey(KeyCode.Q))
        {

            detail1.rotation = Quaternion.RotateTowards(detail1.rotation, Quaternion.Euler(new Vector3(-30, 0, 0)), 30f * Time.deltaTime);


        }
       
       
    }
}

Be more specific. When you say “rotate in x”, what do you mean? Based on the keys being used, I think you mean to rotate left and right (like shaking your head no), but when you use the X rotation, you’re rotating around the X axis. Rotating on the X axis actually rotates like you’re nodding your head. If you want to rotate left and right, you need to use the Y axis.

Sorry, but I have a turn on the x axis going up and down, closer to the point I still can not understand why it does this?

When you describe rotations with Euler angles, what you’re actually describing with each number is the axis around which it’s rotating. The X axis points to the right, Y axis points up, and Z axis points forward.

So now, rotate around the axis that points to the right… and your object “nods” up and down. That’s what you’re doing now.

What you want to do (I assume) is have it turn left and right, which means you want it to rotate around the axis that points upward. That’s the Y axis. So, your Euler parameters should be (0,30,0) rather than (30,0,0).

1 Like

I have a cannon and a turret, the cannon must go up and down, the turret to the right and left, and everything works well, only when I rotate the TOWER, the cannon no longer rotates along those axes along which I set

Oh, ok. That changes things. This is why it’s important to be clear and precise when describing problems.

You need to be using localRotation for this, rather than rotation, in all 4 places where you use rotation in this code. “rotation” means the worldspace rotation, but you actually want the rotation relative to the tower - its local rotation.

yea

maybe it’s stupid but I tried to do it and nothing changed

 detail1.localRotation = Quaternion.RotateTowards(detail1.rotation, Quaternion.Euler(new Vector3(30, 0, 0)), 30f * Time.deltaTime);

sorry corrected, missed such a trifle, thanks for the advice