简体   繁体   中英

Per Pixel collision detection

Creating a 2D Hell Theme Helicopter game in XNA.

Having a few problems with my Per Pixel collision detection in that it is returning true when the colours are not colliding.

Here is the code for my Per Pixel:

class PPCollisionDetection
{
    public Rectangle rect1, rect2;
    public Color[] data1, data2;

    public PPCollisionDetection()
    {
    }

    public Boolean Detect(Rectangle r1, Rectangle r2, Texture2D t1, Texture2D t2)
    {
        data1 = new Color[t1.Width * t1.Height];
        t1.GetData(data1);
        data2 = new Color[t2.Width * t2.Height];
        t2.GetData(data2);

        rect1 = r1;
        rect2 = r2;

        int top = Math.Max(rect1.Top, rect2.Top);
        int bottom = Math.Min(rect1.Bottom, rect2.Bottom);
        int left = Math.Max(rect1.Left, rect2.Left);
        int right = Math.Min(rect1.Right, rect2.Right);

        for (int y = top; y < bottom; y++)
            for (int x = left; x < right; x++)
            {
                Color colour1 = data1[(x - rect1.Left) +
                                        (y - rect1.Top) * rect1.Width];
                Color colour2 = data2[(x - rect2.Left) +
                                        (y - rect2.Top) * rect2.Width];

                if (colour1.A != 0 && colour2.A != 0)
                   return true;
            }
        return false;
    }
}

And here is where I call Detect:

if (new Rectangle((int)Helicopter.position.X,(int) Helicopter.position.Y,(int)Helicopter.HelicopterAnimation.Rectangle.Width,(int)Helicopter.HelicopterAnimation.Rectangle.Height).Intersects(stalagtiteRectangle))
{
    if (collDetect.Detect(new Rectangle((int)Helicopter.position.X, (int)Helicopter.position.Y, (int)Helicopter.HelicopterAnimation.Rectangle.Width, (int)Helicopter.HelicopterAnimation.Rectangle.Height), stalagtiteRectangle, Helicopter.HelicopterAnimation.animation,
         stalagtites))
    {
        touched = true;
    }
    else
    {
        touched = false;
    }
}

You don't really need the first rectangle collision since you're already checking with the per-pixel collision.

And I believe it should be:

t1.GetData<Color>(data1);
t2.GetData<Color>(data2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM