I think I had almost this exact problem yesterday! Hopefully my solution is of help to you.
I generate a Vector3 bodyLook which points in the direction I want my character to face (derived from joypad stick input). myBody is the actual GameObject of the entity I want to rotate. Then I use the following code to generate the rotation:
float a = Vector3.Angle(bodyLook, myBody.transform.forward );
float r = Vector3.Angle(bodyLook, myBody.transform.right);
float l = Vector3.Angle(bodyLook, myBody.transform.forward - myBody.transform.right );
if (a>0) {
float rate = a/turnDrag;
if (l>r) {
myBody.transform.Rotate (new Vector3(0f,rate,0f));
}else {
myBody.transform.Rotate (new Vector3(0f,-rate,0f));
}
}
turnDrag is a float that specifies an amount of drag on the rotation (think I find 10f works quite well, bigger = slower)
This works for me, hopefully this is of some help/use, really need to check that a is bigger than something other than 0, perhaps 0.1, otherwise you get a bit of a wobble when you get to your desired angle.
↧