Game Development Reference
In-Depth Information
// [ Index of first car, Index of second car, X impulse, Y impulse ].
var Impulses = [];
for (var i = 0; i < Cars.length; i++)
{
// Move the cars. X and Y are the coordinates of the center of the car.
Cars[i].X += Cars[i].VX;
Cars[i].Y += Cars[i].VY;
// Check for proximity to the left and right walls.
if (Cars[i].X <= GP.CarRadius || Cars[i].X >= GP.GameWidth - GP.CarRadius)
{
// If we are going towards the wall, then give an impulse. Note that, in the
// game frame following a collision with the wall, the car may still be in close
// proximity to the wall but will have velocity pointing away from it. We should
// not treat that as a new collision. That is the reason for this code.
if ((Cars[i].X <= GP.CarRadius && Cars[i].VX <= 0)
|| (Cars[i].X >= GP.GameWidth - GP.CarRadius && Cars[i].VX >= 0))
{
Impulses.push([i, null, 2 * Cars[i].VX, 0]); // Turn the car around.
}
// Make the walls truly rigid. If the car pushed into the wall, push it back out.
if (Cars[i].X <= GP.CarRadius) Cars[i].X = GP.CarRadius;
if (Cars[i].X >= GP.GameWidth - GP.CarRadius)
Cars[i].X = GP.GameWidth ñ GP.CarRadius;
}
// Same as above, but now for the top and bottom walls.
if (Cars[i].Y <= GP.CarRadius || Cars[i].Y >= GP.GameHeight - GP.CarRadius)
{
if ((Cars[i].Y <= GP.CarRadius && Cars[i].VY <= 0)
|| (Cars[i].Y >= GP.GameHeight - GP.CarRadius && Cars[i].VY >= 0))
{
Impulses.push([i, null, 0, 2 * Cars[i].VY]);
}
if (Cars[i].Y <= GP.CarRadius) Cars[i].Y = GP.CarRadius;
if (Cars[i].Y >= GP.GameHeight - GP.CarRadius)
Cars[i].Y = GP.GameHeight ñ GP.CarRadius;
}
// Now that collisions with walls have been counted, check for collisions between
// cars. Two cars have collided if their centers are within 2 * GP.CarRadius, i.e.
// if they overlap at all.
// Note the bounds of this for loop. We don't need to check all the cars.
for (var j = i + 1; j < Cars.length; j++)
{
// Euclidean distance between the centers of the two cars.
var DistSqr = (Cars[i].X - Cars[j].X) * (Cars[i].X - Cars[j].X)
+ (Cars[i].Y - Cars[j].Y) * (Cars[i].Y ñ Cars[j].Y);
if (Math.sqrt(DistSqr) <= 2 * GP.CarRadius)
{
// The impulses from a two dimensional elastic collision.
// Delta = (r_j - r_i) . (v_i - v_j) / |r_j - r_i|^2.
Search WWH ::




Custom Search