Rotating Tank Turret with correct angle

I have a newbie question

I have a simple tank with a turret on it. I need the turret to point a location pointed by mouse and I’ve managed to do it with code below:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
  
if(Ground.Raycast(ray, out hit, 1000))
{
  position = new Vector3(hit.point.x, hit.point.y, hit.point.z);
  position.y = 0;
}
        
transform.LookAt(position);
transform.Rotate(Vector3.down, 90f);

The turret is child of the Tank object.
My problem is when the body of the Tank has an angle to the ground.

Any advice will be appreciated.

Try to set the rotation of your guntower directly. The Quaternion struct offers a LookRotation where you can specify an up vector. Something like this should do the trick:

turretTransform.Rotation = Quaternion.LookRotation(lookPosition - tankPosition, tankUpVector);

Here’s the documentation:

I fear you may have to split the rotation in two parts.

First, the turret itself can rotate just around one axis (pretty much transform.up on the turret).
Second, the gun can turn around another axis (transform.right).

That means that you have to split the rotation into different components.

You could, for example, use Quaternion.eulerangles. That gives you the pitch, yaw, roll axis.

Using the code from Mischa’s answer:

Transform turret;
Transform gun;
  
Vector3 direction = position - transform.position;
Quaternion rotation = Quaternion.LookRotation(direction);
Vector3 eulers = rotation.eulerAngles;
  
turret.Rotate(turret.up,eulers.y);
gun.Rotate(gun.right,eulers.x);

Something along those lines might work.

Vector3 aimVector = playerPosition - transform.position;
aimVector.y = 0.0f;
Quaternion newRotation = Quaternion.LookRotation(aimVector, transform.up);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * rotateSpeed);

Considering it’s a turret which can only rotate in one axis that will be y!
So rotate the turret in y axis only!

Follow this rts tutorial and most of your upcoming problems will be solved!

Maybe it will be useful to someone. Tank turret rotation: