Question

I'm currently trying to write a collision detection method for a 2D game and I'm stuck.

The intersects() method is called by the player passing the enemy, and the coordinates of the player and enemy. An ImageMask object has a 2 dimentional boolean array corresponding to the mask of the sprite. The masks are scaled 4 times because the sprites are 16x16 and scaled up to 64x64 in the game.

public boolean intersects(ImageMask other, int tx, int ty, int ox, int oy) {
    boolean[][] otherMask = other.getMask();
    if ((tx+mask.length*4<ox)         // This checks if the sprites
            || ty+mask[0].length*4<oy // aren't close to each other.
            || ox+otherMask.length*4<tx
            || oy+otherMask[0].length*4<ty)
        return false;

    //This stuff isn't working.
    for (int i=0;i<mask.length;i++) {
        for (int j=0;j<mask[i].length;j++) {
            for (int k=0;k<otherMask.length;k++) {
                for (int l=0;l<otherMask[k].length;l++) {
                    if ((tx+i*4)<=(ox+k*4) && (tx+i*4+4)>=(ox+k*4)
                            && (ty+j*4)<=(oy+l*4) && (ty+j*4+4)>=(oy+l*4+2)
                            && mask[i][j] && otherMask[k][l]) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

This isn't working very well; sometimes it works as expected, but sometimes it reports collisions when the entities aren't touching, or fails to do so when the entities are on top of each other. How should I fix this to make collision detection work?

Was it helpful?

Solution

The if statement should read

if ((tx+i*4)<=(ox+k*4+4) && (tx+i*4+4)>=(ox+k*4)
        && (ty+j*4)<=(oy+l*4+4) && (ty+j*4+4)>=(oy+l*4+2)
        && mask[i][j] && otherMask[k][l])

Also, looking at the rest of the project, you messed up x and y when initializing the ImageMask.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top