在HTML5画布上绘制X形状并检查与边框的碰撞 [英] Drawing an X shape on a HTML5 canvas and checking for collisions with a border
问题描述
我正在使用HTML 5进行迷宫游戏。
I am working on a maze game in HTML 5.
这是我用来在画布上绘制X的功能(使用触摸板,用户将通过迷宫导航X.
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).
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函数,主要是在这段代码中:
The problem is in the checkcollision function, mainly in this piece of code:
ctx.getImageData(checkx, checky, 16, 16);
我正在寻找一种最佳方式来检查所有占用的空间画布上的X。
我使用的代码中有更多注释。
There are more comments in the code i used.
问题:
1.有时,X稍微超越边界
2.有时候,X不接近,让它与边界之间有几个像素。
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.
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位置开始的矩形一个角落。
I believe the getImageData gets a rectangle which starts from the x,y position in a corner.
所以也许有一种方法可以使用checkx和checky作为中心的坐标来绘制它并检索一个16像素宽的正方形
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
推荐答案
哇,写这个问题说清楚了:
Wow, writing the question made it clear:
var imgd = ctx.getImageData(checkx - xdim, checky - xdim, 16, 16);
Ty guys
这篇关于在HTML5画布上绘制X形状并检查与边框的碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!