簡體   English   中英

在HTML5畫布上繪制X形狀並檢查是否有邊框沖突

[英]Drawing an X shape on a HTML5 canvas and checking for collisions with a border

我正在使用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會稍微越過邊界2.有時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像素寬的正方形

哇,寫這個問題很清楚:

var imgd = ctx.getImageData(checkx - xdim, checky - xdim, 16, 16);

伙計們

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM