I'm currently programming a 2d game where the player moves around on a rectangular playing field. The player has a direction and a velocity. What is the best way to limit the player's movement so he/she cannot move past the boundaries of the playing field?




If your game is running iterations/frames, where each iteration takes up a certain amount of real time, you can figure out whether the velocity vector for the player will cause them to cross the boundary. How simple or complicated this calculation needs to be depends on how complicated your boundary is.

Some basic ballistic physics...

Measure the increment of time, t, between iterations. If your player's position is a set of coordinates, x0 (x0_x, x0_y), and the velocity is a vector v (v_x, v_y), the position at the next iteration can always be calculated as:

x = x0 + v*t => (x_x = x0_x + v_x*t, x_y = x0_y + v_y * t)

If the player is accelerating at a constant rate a during that interval:

x = x0 + v*t + 1/2 a*(t^2) => (x0_x + v_x*t + 0.5*a_x*t*t, x0_y + v_y*t + 0.5*a_y*t*t)

All of the above math is just to predict what the player's next x and y position will be.

Determine whether the destination coordinates cross the boundary. If the boundary is a simple rectangle (0 <= x <= 400, 0 <= y <= 300, let's say), you can detect whether a boundary is crossed:

if (x_x < 0) ...
if (x_x > 400) ...
if (x_y < 0) ...
if (x_y > 300) ...

When the boundary is crossed, instead of moving the player that direction, you can do a couple of things:

  • Stop them at the boundary (if x_x < 0, set v_x = 0)
  • "Bounce" them at the boundary (if x_x < 0, set v_x = -v_x)
  • "Wrap around" and put them on the other side of the screen (if x_x < 0, set x_x = 400 + x_x)

If the boundary is more complicated (like a map), you will have to do collision detection.

If you decide to stop them at the boundary or bounce them, you may wish to add in a margin equal to half the width or height of the player's icon (if the player's coordinates are in the center of the icon), so that the player's icon doesn't move partway off of the screen.

Hope this helps.

  • \$\begingroup\$ Wow, thanks a lot, I never thought to check if the player would cross the boundary before moving it. \$\endgroup\$ – DLiKS Dec 31 '10 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.