简体   繁体   English

在HTML5画布上绘制X形状并检查是否有边框冲突

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

I am working on a maze game in HTML 5. 我正在使用HTML 5开发迷宫游戏。

Here is the function which I use to draw an "X" on the canvas (using the touchpad, the user will navigate the X through the labyrinth). 这是我用来在画布上绘制“ 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();       
}

The problem is in the checkcollision function , mainly in this piece of code: 问题在checkcollision函数中 ,主要在这段代码中:

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

I am looking for an optimal way to check all the space that is taken up by the "X" on the canvas. 我正在寻找一种检查画布上“ X”占用的所有空间的最佳方法。

There are more comments in the code i used. 我使用的代码中还有更多注释。

Issues: 1. Sometimes, the X goes a little passed the border 2. Sometimes, the X doesn't get close, letting a few pixels between it and the border. 问题: 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;
    }

I believe the getImageData gets a rectangle which starts from the x,y position in a corner. 我相信getImageData会获得一个矩形,该矩形从角落的x,y位置开始。

So maybe there is a way to draw it using the checkx and checky as the coordinates for the center and retrieve a square 16 pixels wide 因此,也许有一种方法可以使用checkx和checky作为中心坐标来绘制它,并检索一个16像素宽的正方形

Wow, writing the question made it clear: 哇,写这个问题很清楚:

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

Ty guys 伙计们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM