Search code examples
javacollision-detectionlwjgl

LWJGL Collision Detection flaw


I am currently using this code for 2D Collision Detection in my Space Invaders like game :

for(byte k = 0; k < enemies.length; k++) {
    if(shot.x < enemies[k].getTexture().getImageWidth() && shot.x  > enemies[k].pos.x) {
            if(shot.y - 1.2f * frameCount < enemies[k].pos.y && shot.y - 1.2f * frameCount > Main.enemies[k].pos.y - enemies[k].getTexture().getTextureHeight()) {
                    Main.enemies[k].hit = true;
            }
    }
}

However, there is one major flaw in this type of collision detection; I can only detect collisions coming form below. Why is this?


Solution

  • The reason you are only getting collisions from the bottom is that your bounds checking has some errors. Below I have given a fixed and slightly clearer version, and I assume that shotWidth and shotHeight can be calculated. (I have left out the part regarding frameCount, but it should be possible to edit it in again if needed).

    final int shotX = shot.x;
    final int shotY = shot.y;
    final int shotWidth = ?
    final int shotHeight = ?
    for(byte k = 0; k < enemies.length; k++) {
        final int enemyX = enemies[k].pos.x;
        final int enemyY = enemies[k].pos.y;
        final int enemyWidth = enemies[k].getTexture().getImageWidth();
        final int enemyHeight = enemies[k].getTexture().getImageHeight();
    
        if(     shotX < enemyX + enemyWidth &&
                shotX + shotWidth < enemyX &&
    
                shotY < enemyY + enemyHeight &&
                shotY + shotHeight < enemyY) {
    
            Main.enemies[k].hit = true;
        }
    }