I recently needed to refresh my math a bit in order to detect the intersection of a line and a rectangle, or a line and a point. For everything so far, I had been using rectangular bounding boxes and simply using the standard builtin Rectangle .Intersects() functionality:
if (bullets[i].Rect.Intersects(zombie.Rect))
{
zombie.alive = false;
bullets[i].alive = false;
player1.score += 1;
//chance for ammo drop
bool dropAmmo = (random.NextDouble() > 0.9);
if (dropAmmo)
{
SpawnPickupable(zombie.position, Vector2.Zero, PickupableType.Ammo);
}
break;
}
if (bullets[i].Rect.Intersects(enemy.Rect))
{
enemy.alive = false;
bullets[i].alive = false;
//...
}
This worked well, but with a new laser weapon I wanted to test for the collision between a line and a rectangle. I didn't need pixelperfect collision, so I ended up going with using linepoint collision as an approximation. In a nutshell, I do this:
Given a line segment AB, and a point p...
A) Find the point on the line segment nearest to the point p
B) Calculate the distance between the nearest point and p
C) Compare the distance between the points to a collision threshold distance, and if point p is closer to the line than that threshold distance I count it as a collision and react accordingly.
