Turret rotation on one axis problems

I’ve been trying to make a turret (1 of its parts) rotate on only one axis, namely the Y axis. However, I’ve had no luck in doing so and solutions found online did not me help fix the problem. So I came to the last place where I might get some help.

Quaternion lookRotation = Quaternion.LookRotation(targetInterceptPos - PartToRotate.position, Vector3.up);
Vector3 rotation = Quaternion.Slerp(PartToRotate.rotation, lookRotation, Time.deltaTime * BaseTurnSpeed).eulerAngles;
PartToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);

The base of the turret (named PartToRotate) should rotate only on the Y axis. However, if the parent of the turret (a ship) starts turning, lets say to (0, 0, 45) then the turret will rotate on the X and Z axis to accomodate this rotation for some reason.

If I try to use localRotation, the turrets don’t even rotate on the Y axis anymore when the ship starts to move.

“targetInterceptPos” is a Vector3 variable used for a look ahead calculation. If need be I can post the code for that as well.

Thank you.

I’ve managed to solve it I think. The turrets no longer rotate on the X or Z axis. If anyone stumbles upon this question and has a better solution feel free to share it, for everyone else, here is the code that fixed it for me, maybe it will help you too.

Keep in mind that I wrote the code with a 2 part turret in mind, one which contains a base rotator and the turret itself.

//First part - Rotates the base of the turret
Quaternion lookRotation = Quaternion.LookRotation(targetInterceptPos - PartToRotate.position, Vector3.up);
PartToRotate.rotation = Quaternion.RotateTowards(PartToRotate.rotation, lookRotation, Time.deltaTime * BaseTurnSpeed);
PartToRotate.localEulerAngles = new Vector3(0, PartToRotate.localEulerAngles.y, 0);

//Second part - Rotates the turret itself
Quaternion turretLookRotation = Quaternion.LookRotation(targetInterceptPos - TurretRotator.position);
if (TurretRotator.localEulerAngles.x > 270)
{
 TurretRotator.rotation = Quaternion.RotateTowards(TurretRotator.rotation, turretLookRotation, Time.deltaTime * TurretTurnSpeed);
 TurretRotator.localEulerAngles = new Vector3(TurretRotator.localEulerAngles.x, 0, 0);
 }
else if (TurretRotator.localEulerAngles.x < 10)
 {
  TurretRotator.rotation = Quaternion.RotateTowards(TurretRotator.rotation, turretLookRotation, Time.deltaTime * TurretTurnSpeed);
  TurretRotator.localEulerAngles = new Vector3(TurretRotator.localEulerAngles.x, 0, 0);
  }

I would try a simple azimuth calculation for it.

float angle = Mathf.Atan2(target.transform.position.x - partToRotate.position.x, target.transform.position.z - partToRotate.position.z) * Mathf.Red2Deg;

transform.rotation = Quaternion.Euler(0f,angle,0f);

you could slerp to this angle once you see how it works.