我正在使用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不会靠近,在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);
泰家伙
原文地址:https://codeday.me/bug/20191013/1906943.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。