Why does this collision detection technique not affect all objects?

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();
    }
}
+3
source share
1 answer

I think you made a mistake with the code. You just have to separate the X and Y axes when comparing distances if the distance Y is less than the width and the distance X is less than the height than in a collision.

, - , . , , x.axis - , y.axis - . ;-)

:

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--;
}

, , . . , .

PS: , - , , …

+1

Source: https://habr.com/ru/post/1775029/


All Articles