- Home /
(c#) NPC rotator
I have an npc that uses vector3.up as its forward vector so that it moves around on an x y axis and rotates around the z. I want rotation around the other axis to be constrained, which I have set in the rigidbody component. I am using this bit of code here for my npc rotation
public void RotationControl(GameObject gO){ //for direction 0 is right left is 1
//Rotates toward the target
Quaternion targetRotation = Quaternion.LookRotation (rotationDir, Vector3.forward);
Debug.Log ("rotationDir: " + rotationDir);
gO.rigidbody.transform.rotation = Quaternion.Slerp(gO.transform.rotation, targetRotation, Time.deltaTime * 2.0f);
}
which makes the npc rotate a few hundred points around all three axis. I do have rotation constrained on the x and y through the rigidbody which seems to be being ignored.
In the code above the rotationDir variable is a vector 3 that is being passed from a raycasthit.point. (which I'm using two of to determine which direction to rotate in)
So thats all the background info I can provide, though I'll be happy to provide more if questions are asked. Does anyone have any ideas or clues on how I can fix this problem? I've been working at it for longer than I care to admit and just want it over.
Answer by robertbu · Nov 04, 2014 at 05:52 AM
For 2D with Vector3.up as the forward, and assuming that rotationDir is on the XY plane, you can do this:
float angle = Mathf.Atan2(rotationDir.y, rotationDir.x) * Mathf.Rad2Deg;
Quaternion targetRotation = AngleAxis(angle + 90, Vector3.forward);
gO.transform.rotation = Quaternion.Slerp(gO.transform.rotation, targetRotation, Time.deltaTime * speed);
Replace 'speed' by 2.0f, or define a variable called 'speed' and initialize it to 2.0f.