1

HTML 5 で迷路ゲームを作成しています。

キャンバスに「X」を描画するために使用する関数を次に示します (タッチパッドを使用して、ユーザーは X を迷路内でナビゲートします)。

dim = 8;

function rect(x,y,xdim){
    ctx.beginPath();
    ctx.moveTo(x - xdim, y - xdim);
    ctx.lineTo(x + xdim, y + xdim);
    ctx.moveTo(x + xdim, y - xdim);
    ctx.lineTo(x - xdim, y + xdim);
    ctx.strokeStyle = '#FF5000';
    ctx.stroke();       
}

問題はcheckcollision 関数にあり、主に次のコード部分にあります。

ctx.getImageData(checkx, checky, 16, 16);

キャンバス上の「X」が占めるすべてのスペースをチェックする最適な方法を探しています。

私が使用したコードには、さらにコメントがあります。

問題: 1. X が境界線を少し超えることがあります。

function checkcollision(checkx, checky){
        var collision = 0;
        /*
            User presses an arrow key

            Calculate where that would move the square to.

            Look at all of the pixels on the maze image that the square will cover
            in its new position (our square is 15x15 so we look at 225 pixels)

            Are any of the pixels black (the maze is white with black borders. 
            If a pixel is black that means the square would collide with a border)

            YES: then do not move

            NO: then move
        */
        var imgd = ctx.getImageData(checkx, checky, 15, 15);
        pix = imgd.data;
        for (var i = 0; n = pix.length, i < n; i += 4){
            if (pix[i] == 0) {
                collision = 1;
            } else if(pix[i] == 255 && pix[i + 1] == 0){
                winner = "yes";
            }
        }
        return collision;
    }

getImageData は、隅の x、y 位置から始まる長方形を取得すると思います。

したがって、中心の座標としてcheckxとcheckyを使用して描画し、幅16ピクセルの正方形を取得する方法があるかもしれません

4

1 に答える 1