Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

Thanks,

DLiKS

share|improve this question

1 Answer 1

up vote 11 down vote accepted

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.

share|improve this answer
    
Wow, thanks a lot, I never thought to check if the player would cross the boundary before moving it. –  DLiKS Dec 31 '10 at 21:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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