I am currently developing a game in which a player can shoot bullets to destroy asteroids.
At the moment, this collision detection code affects 1 or 2 asteroids, but not everything that appears on the screen. I think the following code has a flaw, but I'm not sure where.
public void CollisionDetection()
{
for (int i = 0; i < ship.bullets.Count; i++)
{
Rectangle shipRectangle = new Rectangle((int)ship.ShipPosition.X, (int)ship.ShipPosition.Y,
shipTexture.Width, shipTexture.Height);
for (j = 0; j < asteroidPositions.Count; j++)
{
asteroidRectangle = new Rectangle((int)asteroidPositions[j].X, (int)asteroidPositions[j].Y,
asteroidTexture.Width, asteroidTexture.Height);
Vector2 position1 = asteroidPositions[j];
Vector2 position2 = ship.bullets[i];
float Cathetus1 = Math.Abs(position1.X - position2.X);
float Cathetus2 = Math.Abs(position1.Y - position2.Y);
Cathetus1 *= Cathetus1;
Cathetus2 *= Cathetus2;
distance = (float)Math.Sqrt(Cathetus1 + Cathetus2);
if ((int)distance < asteroidTexture.Width)
{
score += 20;
asteroidPositions.RemoveAt(j);
j--;
}
}
if (shipRectangle.Intersects(asteroidRectangle))
{
lives--;
asteroidPositions.RemoveAt(j);
}
if (lives == 0)
Exit();
}
}
source
share