Character Orientation Code Resource

Does anyone know some good resource to really understand what is happening with these lines of code? I mean I understand it but I don’t really know how or why these things exist.

                // Character orientation
                if (_MoveDirection.Length() > 0.001)
                {
                    _YawOrientation = MathUtil.RadiansToDegrees((float)Math.Atan2(-_MoveDirection.Z, _MoveDirection.X) + MathUtil.PiOverTwo);
                }
                Unit.Transform.Rotation = Quaternion.RotationYawPitchRoll(MathUtil.DegreesToRadians(_YawOrientation), 0, 0);

Short version: It makes the component face in the direction it’s moving.

Long version:
What seems to be happening here is the following:
First there’s a check to see if the component passed a certain threshold for moving (if (_MoveDirection.Length() > 0.001)). You don’t want for example analog stick jitter to affect player movement. Therefore the threshold.

The following line converts the component’s movement direction to an angle (rotation around the Y axis is referred to as Yaw):
_YawOrientation = MathUtil.RadiansToDegrees((float)Math.Atan2(-_MoveDirection.Z, _MoveDirection.X) + MathUtil.PiOverTwo);

The last line converts the angle to radians and constructs a new quaternion from pitch, yaw and roll (rotations around X, Y and Z) and assigns it to the component’s rotation:
Unit.Transform.Rotation = Quaternion.RotationYawPitchRoll(MathUtil.DegreesToRadians(_YawOrientation), 0, 0);

1 Like

Thank you for responding, Yea I figured out what suppose to represent the trouble I’m having is getting it to set my model in the direction my model is moving each frame update. I cant seem to understand the how to make it face that direction.

What about the current code doesn’t work for you?

Yes I found that my model was not facing -z for forward. After fixing that it worked just fine thank you for the help.

1 Like