Vector3.Angle making my object oscilate...

I have a turret that is going to follow the mouse. The gun part of the turrent only goes up and down and the base it is attached to will spin. The gun I got to work no problem, but when I try to get the turret to spin the thing goes crazy and keeps going in a circle regardless if the mouse has moved. I mean if the mouse doesn’t move at all the turret still does.

The code I have is:

baseObject.eulerAngles.z = Vector3.Angle(baseObject.position - rayHit.point, baseObject.forward);

A couple of issues. First, you are setting only one axis of eulerAngles. This can cause problems. See the note in the Transform.eulerAngles Reference. The second problem is that Vector3.Angle does not return a signed angle. If you need to, you can get absolute 2D angles of vectors if you project them onto a plane using Mathf.Atan2(). But I suggest a different approach for a turret.

  • Make sure the forward of your turret model points down positive Z. If it does not, you can compensate with an empty game object.
  • Get the point you want the turret to look at.
  • Make it’s ‘y’ value of that point match the ‘y’ value of the turret.
  • Use Transform.LookAt() to rotate the turret.

Based on the line of code above, I’m assuming that rayHit.point is the point you want the turret base to point at:

var v3Pos = rayHit.point;
v3Pos.y = transform.y;

baseObject.rotation = Quaternion.SetLookRotation(
(rayHit.point - baseObject.position).normalized,