Search code examples
c#xnacollision

Collision Code isn't working, despite several checks


I am working on Collision in XNA. Some reason, despite my many tries, it doesn't work. If I touch it, it will work. But sometimes randomly it will just stop running as if a collision occured. The way it works is there are fifty 20px by 20px squares. If your square touches another square in any way, then the game is over.

checkcollision()
    {
        for (int i = 0; i < 50; i++)
        {
            if ((loc.X + me.Width > enemyloc[i].X) && (loc.Y + me.Height > enemyloc[i].Y) && (loc.Y < enemyloc[i].Y) && (loc.X < enemyloc[i].X)) { return true; }
            if ((loc.X > enemyloc[i].X) && (enemyloc[i].X + enemy[i].Width > loc.X) && (loc.Y + me.Height > enemyloc[i].Y) && (loc.Y < enemyloc[i].Y)) { return true; }
            if ((loc.X > enemyloc[i].X) && (loc.X < enemyloc[i].X + enemy[i].Width) && (loc.Y > enemyloc[i].Y) && (loc.Y < enemyloc[i].Y + enemy[i].Height)) { return true; }
            if ((loc.X < enemyloc[i].X) && (loc.X + me.Width > enemyloc[i].X) && (loc.Y < enemyloc[i].Y) && (loc.Y < enemyloc[i].Y + enemy[i].Height)) { return true; }
        }
        return false;
    }

Solution

  • I agree that this code looks a bit too complicated. I would suggest storing your enemy and player collision boxes as instances of the Rectangle struct. The Rectangle struct provides a method called Contains which is defined as:

    public bool Contains(int x, int y);
    

    This method will return true if the point defined at x and y exists in the rectangle. Thus using this struct the code will become much simpler:

    public bool checkcollision(Rectangle player)
    {
        for (int i = 0; i < enemy.Length; i++)
        {
            if (enemy[i].Contains(player.Left, player.Top)
                || enemy[i].Contains(player.Right, player.Top)
                || enemy[i].Contains(player.Left, player.Bottom)
                || enemy[i].Contains(player.Right, player.Bottom))
            {
                return true;
            }
        }
        return false;
    }