Search code examples
mathlualogiclove2d

horizontal movement in game (rotated player)


In my world I have a character wich is always rotated towards the mouse.

It is very logical that when the player moves forward or backward, that the character's x coordinate equals it's x coordinate minus (or plus) the cosine of its x coordinate. And the same for its y coordinate, but instead of the cosine, you take the sine.

Like this:

player.x = player.x + math.cos(player.r) * dt * 120 --forward
player.y = player.y + math.sin(player.r) * dt * 120

player.x = player.x - math.cos(player.r) * dt * 120 --backward
player.y = player.y - math.sin(player.r) * dt * 120

But what if I also want to make the player run sideways?


Solution

  • If you want to move sideways, you can simply add or subtract 90 degrees (in radians, that is π/2) from your r before calculating the sin/cos velocity vector.