- Home /
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);
If either robertbu's answer or my answer have helped you, can you please tick the circular grey tick icon on one/both of our answers? This lets others know that the question is answered and makes it more likely that others will want to answer your questions in the future.
Sorry RL kept me away from this for a while and I was unable to test it until now.
Answer by Khada · Mar 05, 2013 at 07:29 AM
baseObject.rotation = Quaternion.SetLookRotation(
(rayHit.point - baseObject.position).normalized,
Vector3.up);
I used code Derived from this, still had to clamp the X and reverse the Y but I got something that overall works ty.
Answer by robertbu · Mar 05, 2013 at 07:26 AM
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;
transform.LookAt(v3Pos);
Your answer
Follow this Question
Related Questions
Quaternion Equivalent of restricting an axes rotation to zero 3 Answers
How to add a rotation to this? 1 Answer
How to clamp the rotation of this? 0 Answers
Using MouseLook script with LookAt function 2 Answers
problems with quaternion rotations 4 Answers