Collision Detection Implementation

前端 未结 2 872
温柔的废话
温柔的废话 2021-01-03 15:09

I have a collision detection class that works by finding the distance between the centres and whether that distance is small enough to be a collision (see Collision Detectio

相关标签:
2条回答
  • 2021-01-03 15:43

    The best way would to implement per pixel collision detection when the images are overlapping you can read more about this in the following links

    http://www.codeproject.com/KB/game/collision3.aspx

    Per-pixel collision problem in C#

    I also did a problem like this for a project a few years ago when I needed to detect if two circles overlapped where i used the following code

        public static bool Intersect(Rectangle rectangle1, Rectangle rectangle2)
        {
            if (((rectangle1.X < (rectangle2.X + rectangle2.Width)) && (rectangle2.X < (rectangle1.X + rectangle1.Width))) && (rectangle1.Y < (rectangle2.Y + rectangle2.Height)) && (rectangle2.Y < (rectangle1.Y + rectangle1.Height)))
            {
                Vector2 rect1Centre = new Vector2(rectangle1.X + rectangle1.Width / 2, rectangle1.Y + rectangle1.Height / 2);
                Vector2 rect2Centre = new Vector2(rectangle2.X + rectangle2.Width / 2, rectangle2.Y + rectangle1.Height / 2);
                double radius1 = ((rectangle1.Width / 2) + (rectangle1.Height / 2)) / 2;
                double radius2 = ((rectangle2.Width / 2) + (rectangle2.Height / 2)) / 2;
    
                double widthTri = rect1Centre.X - rect2Centre.X;
                double heightTri = rect1Centre.Y - rect2Centre.Y;
                double distance = Math.Sqrt(Math.Pow(widthTri, 2) + Math.Pow(heightTri, 2));
    
                if (distance <= (radius1 + radius2))
                    return true;
            }
            return false;
        }
    

    Not very nice code but I wrote it doing my first XNA game

    0 讨论(0)
  • 2021-01-03 15:43

    I had the same problem recently. Circle overlap is easy to determine. With ellipses it's trickier, but not that bad. You play around with the ellipse equation for a while, and the result comes up:

    //Returns true if the pixel is inside the ellipse
    public bool CollisionCheckPixelInEllipse(Coords pixel, Coords center, UInt16 radiusX, UInt16 radiusY)
    {
       Int32 asquare = radiusX * radiusX;
       Int32 bsquare = radiusY * radiusY;
       return ((pixel.X-center.X)*(pixel.X-center.X)*bsquare + (pixel.Y-center.Y)*(pixel.Y-center.Y)*asquare) < (asquare*bsquare);
    }
    
    // returns true if the two ellipses overlap
    private bool CollisionCheckEllipses(Coords center1, UInt16 radius1X, UInt16 radius1Y, Coords center2, UInt16 radius2X, UInt16 radius2Y)
    {
        UInt16 radiusSumX = (UInt16) (radius1X + radius2X);
        UInt16 radiusSumY = (UInt16) (radius1Y + radius2Y);
    
        return CollisionCheckPixelInEllipse(center1, center2, radiusSumX, radiusSumY);
    }
    
    0 讨论(0)
提交回复
热议问题