Reputation: 93
I want to move my character in any direction with an analog gamepad input in the same maximum constant speed.
Typically for 8 directional movement, I would just multiply the player's speed by a constant based on the type of direction.
ORTHOGONAL_SPEED = 2
DIAGONAL_SPEED = 1.414
what I have is a decimal of the current axes from the analog input.
joy1_axisDir1 = a number between -1(left) and 1(right)
joy1_axisDir2 = a number between -1(up) and 1(down)
this what I have now to move the character around the screen.
Lua code:
if joy1_axisDir1 ~= 0 then
player.x = player.x + (player.move_speed * joy1_axisDir1)
end
if joy1_axisDir2 ~= 0 then
player.y = player.y + (player.move_speed * joy1_axisDir2)
end
This results in diagonal movement being noticeably faster than in any other direction.
How do I factor in the direction to limit the player's move speed?
Upvotes: 1
Views: 1648
Reputation: 4217
Use the Pythagorean theorem to find the magnitude of your velocity vector, divide your X and Y velocities by that magnitude, then multiply each by the movement speed you want.
This is basic vector mathematics. You are normalizing a vector then multiplying it by a scalar to get a vector with the magnitude of that scalar and the direction of the original vector.
Upvotes: 2