# Moving character in 3D world with joystick

## Recommended Posts

I'm at a complete loss on how to accomplish this and I haven't been able to find anything online to help. I'm trying to figure out how to move my character through a 3D world using a typical controller with an analog joystick. The more I think about how to do this, the more complex it appears to be. What I've been doing so far is getting the angle the joystick is at by using atan2(y, x) and then setting the rotation of the character to that angle and try to figure out how to make the proper matrices/quaternions. And then on top of that, I need to figure out how to make the character go forward in the same direction the joystick is pressed. I'm doing this using matrices/quaternion/a forward vector but it's just a complete mess (still having a hard time figuring out how to use these and build up the translation matrix properly). Am I even on the right track? This functionality is in almost every 3D game these days so I'm surprised I can't find any tutorial on this. Anyone know of one?

##### Share on other sites
It sounds like you're on the right track. In its simplest form, the process would be to compute the angle using atan2(), as you described, and then compute the forward direction vector as follows:
forward.x = cos(angle);forward.y = sin(angle);
There are other ways you could do it too, such as building a rotation matrix from the angle and then extracting the forward vector from the matrix, or bypassing the matrix entirely and constructing both the forward vector and rotation matrix directly from the joystick 'x' and 'y' values.

Here's some pseudocode showing the basics (+z is assumed to be up):
// Character definition:struct Character {    float angle;    matrix33 orientation;    vector3 position;    vector3 forward;    float speed;    matrix44 transform;};Character character;// ...vector2 joystick = get_joystick_vector();if (joystick.length() > epsilon) {    character.angle = atan2(joystick.y, joystick.x);    character.orientation = matrix_rotation_world_z(character.angle);    character.forward = character.orientation.get_x_axis(); // Assuming +x is forward in local space}character.position += character.forward * character.speed * time_step;character.transform = matrix_affine_transform(character.orientation, character.position);
If that doesn't answer your question, perhaps you could describe in a little more detail what sort of problems you're running into.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628328
• Total Posts
2982099

• 22
• 9
• 9
• 13
• 11