Why is this collision detection method not hitting all objects?
I am currently developing a Game where the player can shoot bullets to destroy asteroids.
At the moment, this code for collision detection is hitting 1 or 2 asteroids, but not all that appear on screen. I think there is a flaw in the following code, 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);
开发者_Python百科 j--;
}
}
if (shipRectangle.Intersects(asteroidRectangle))
{
lives--;
asteroidPositions.RemoveAt(j);
}
if (lives == 0)
Exit();
}
}
I think you got some of the code wrong. You just should separate the X and Y axis during distance comparison, if the Y distance is smaller than the width and the X distance is smaller than the height than there is a collision.
I assume the position is the middle of the object otherwise the algorithm would be far more complicated. I also assume the bullet has virtually no size and that the x.axis is the width and the y.axis is the height. Without seeing the rest of the code its hard to tell ;-)
My suggestion:
Vector2 asteroidPosition = asteroidPositions[j];
Vector2 shipPosotion = ship.bullets[i];
float distanceX = Math.Abs(asteroidPosition.X - shipPosotion.X);
float distanceY = Math.Abs(asteroidPosition.Y - shipPosotion.Y);
if ((int)distanceX < asteroidTexture.Width and (int)distanceY < asteroidTexture.Height )
{
score += 20;
asteroidPositions.RemoveAt(j);
j--;
}
This code is not tested at all, i even don't have a clue which language this actually is. So just take it as inspiration. Hope it will work out.
P.S.: If you are interested I could mail you the source code of some asteroid shooting game I did a while ago to study it…
精彩评论