Search code examples
c#gdi+physicsgame-physics

Physics Engine (Collision Detection C#, GDI+)


I'm currently working on a 2D Game Engine in C# using GDI+ and have gotten to the point where I want to add simple collision detection.

So far, I can check whether or not my player has intersected with another game object using the code below:

public static bool IntersectGameObject(GameObject a, GameObject b)
{
    Rectangle rect1 = new Rectangle((int)a.Position.X, (int)a.Position.Y, a.Sprite.Bitmap.Width, a.Sprite.Bitmap.Height);
    Rectangle rect2 = new Rectangle((int)b.Position.X, (int)b.Position.Y, b.Sprite.Bitmap.Width, b.Sprite.Bitmap.Height);

    return rect1.IntersectsWith(rect2);
}

That's fantastic and I'm happy that I've gotten this far, however I wish to find out whether or not my player has intersected with the top, bottom, left or right side of a game object so that I can stop my player from moving in that direction if say... he collides with a wall. How would I go about doing this? Can some one please help me :)

By the way, game objects have Bitmaps, that are all 32 * 32 pixels, so i don't need per pixel collision

Thank you in advance :)


Solution

  • Computing whether two rectangles intersect is just a matter of a few comparisons (I know you're already using IntersectsWith):

    if (Left > other.Right) return false;
    if (Right < other.Left) return false;
    if (Top > other.Bottom) return false;
    if (Bottom < other.Top) return false;
    return true;
    

    To determine the direction of the collision, you'll have to take into account the possibility that:

    • one rectangle completely contains the other (collides in no direction)
    • it might create a "plus" figure (collides in all directions)
    • one corner of the rectangle could intersect with a corner of other corner (collides in two directions)

    Anyway, to determine whether it has collided on the left side:

    if (Right > other.Left && Right < other.Right && Left < other.Left)
    {
        // the right side of "this" rectangle is INSIDE the other
        // and the left side of "this" rectangle is to the left of it
    }
    

    Last but not least, if you're computing this frame by frame, there's the possibility that an object might "jump over" the other. For more realistic physics you'd have to keep track of time and compute when it would intersect with (each edge of) the rectangle.