Search code examples
javascripthtmlcanvascollision-detectiongame-physics

Pixel Collision Detection Not Working


Here is my game plnkr.

(Edit: another plnkr with one static monster instead of multiple dynamic ones)

Enter or the button will restart the game.

Can anyone tell why the collision detection algorithm taken from here is not working? It seems to detect a hit not accurately (too widely). The demo on their site works great but I'm not sure what I'm doing wrong.

Most relevant piece of code (inside update function):

// Are they touching?


if (heroImage.width) {
    var heroImageData = ctx.getImageData(heroImage.x, heroImage.y, heroImage.width, heroImage.height);
    var monsterImageData;
    for (var i = 0; i < monsters.length; i++) {
        var monster = monsters[i];

        monster.x += monster.directionVector.x;
        monster.y += monster.directionVector.y;

        monsterImageData = ctx.getImageData(monster.monsterImage.x, monster.monsterImage.y, monster.monsterImage.width, monster.monsterImage.height);
        if (isPixelCollision(heroImageData, hero.x, hero.y, monsterImageData, monster.x, monster.y)) {
            stop();
        }
    }
}

Solution

  • As @GameAlchemist pointed out you're taking ImageData for monster and hero from the canvas background, which has already been painted with the background image. Thus will always have alpha value 255 (Opaque).

    Which is being checked in the collision function

    if (
        ( pixels [((pixelX - x ) + (pixelY - y ) * w ) * 4 + 3 /*RGBA, alpha @ 4*/] !== 0/*alpha zero expected*/ ) &&
        ( pixels2[((pixelX - x2) + (pixelY - y2) * w2) * 4 + 3 /*RGBA, alpha @ 4*/] !== 0/*alpha zero expected*/ )
    ) {
        return true;
    }
    

    Instead both the ImageData should be generated by drawing these images to a canvas with nothing painted. Even after doing that collision algorithm doesn't seem to work too well.

    I have created two variables monsterImageData and heroImageData to hold the imageData these variable are loaded only once.

    There's a new canvas in HTML file id=testCanvas. This is used to get image data values for monster and heroes.

    Here is the plunker link for modified code.