Search code examples
androidcollisionrectangles

rectangle collision detection not working


i have a game with bullets and monsters wherein i need to release the bullets and monsters when they collided using rectangles however when the collision occurs the method is not returning true

here is what i did: i set bounds for each bullet/monster

bounds.left = (int)X;
bounds.top = (int)Y ;
bounds.right = (int)X + monsterWidth;
bounds.bottom = (int)Y + monsterHeight;

then made a boolean method

return bounds.intersect((int)X,(int) Y ,(int) X + monsterWidth, (int) Y + monsterHeight);

i have this bounds for both then i call them on the gamethread

int i=0, j=0;
        while (!monster.isEmpty() && monster.size()>i){
            j=0;
            while (!bullets.isEmpty() && bullets.size()>j){
                if(monster.get(i).isColliding(bullets.get(j).getBounds())){
                    Log.v("collided", "Collided!");
                    monster.get(i).setRelease(true);
                    bullets.get(j).setRelease(true);
                }
                j++;
            }
            i++;
        }

i have the log on each for the bounds and both of them are correct left<=right top<=bottom however in the iscolliding method there is no log . i have tried instersects(left,top,right,bottom) but still the same.


Solution

  • This is my rect to rect collision checking method (assuming both rects are axis aligned)

    where x1 is x start
    where x2 is x1 + rect width
    where y1 is y start
    where y2 is y1 + rect height
    

    _x1, _x2, _y1, _y2 is using the same formula but representing the second rectangle.

    bool boolResult = false;
    
        if (x2 >= _x1 && x1 <= _x2 && y2 >= _y1 && y1 <= _y2)
        {
            boolResult = true;
        }
    
    return boolResult;
    

    It's working for me, so see if it can work out for you