I'm working on a simple 2D game (birds eye view). I have projectiles, which are circles. There are barriers around the game level, which are all rectangles (axis aligned). I'd like the projectiles to bounce off the barriers when they collide. I'm not sure how to implement this in my game loop. Guessing it'd be something like this:
void gameLoop() {
Projectile p = ..;
p.updateLocation(p.getVelocity(), p.getDirection());
Barrier intersected = p.intersects(barriers);
if (intersected != null) {
// We hit a barrier after moving on this time tick.
// Figure out where our reflected location off the
// barrier should be now.
Point ptNew = intersected.reflect(p.getLastPoint(), p.getVelocity(),
p.getDirection());
// Our new location after getting bounced off the barrier.
ptNew.setLocation(ptNew);
}
}
So after we move the projectile, we can check if we're intersecting (or completely inside) one of the barriers. If so, do a computation to figure out where our reflected position should be off the barrier given our starting point and velocity/direction.
Thanks
---------- Update ------------------------
A little more specific - given Erik's comments, I do need to make sure the projectiles bounce properly, I can't have them pass through a barrier if their velocity happens to be so fast they go right through on a single game loop iteration.
In that case, I guess I need to test a starting point, velocity, direction, against all barriers (possibly repeatedly) until no more intersections for the velocity are possible. Something like:
void gameLoop() {
Projectile p = ...;
Barrier barrier = moveProjectile(p, barriers);
while (barrier != null && p.stillHasVelocityThisFrame()) {
barrier = moveProjectile(p, barriers);
}
// at this point, the projectile is done moving / bouncing around.
}
void moveProjectile(Projectile projectile,
List<Barrier> barriers)
{
for (Barrier barrier : barriers) {
// tbd
Barrier intersected = test2dVectorAgainstRectangle(
projectile.getPosition(),
projectile.get2dVector());
// the above would test the projectile's vector
// to see if it intersects any barrier, reflect
// off of it if necessary, modify the projectile's
// position, and reduce the available distance it
// can still travel for this frame.
if (intersected) {
return intersected;
}
}
// no intersections.
return null;
}
Yeah this is already getting kind of tricky.
Thanks