我正在尝试用帆布开发一个迷宫游戏。我手动绘制了迷宫,例如
context.moveTo(100,700);
context.lineTo(100,600);
context.lineTo(200,600);
context.lineTo(200,500);
还有更多。我希望通过这些线移动对象,而不会超出这些边界。
为此,我尝试了以下代码:
function right() {
context.clearRect(0, 0, canvas.width, canvas.height);
art();
myImage11.src = "Point.png";
x += 20;
if ((x + 20 < 50)) {
context.clearRect(0, 0, canvas.width, canvas.height);
checkcollision();
if (collision == 1) {
x -= 20;
collision = 0;
}
context.drawImage(myImage11, x, y, 50, 50);
}
我的checkcollision函数
function checkcollision() {
var myImage11 = context.getImageData(x, y, 10, 10);
var pix = myImage11.data;
for (var i = 0; n = pix.length, i < n; i += 4) {
if (pix[i] == 0) {
collision = 1;
}
}
}
但它不起作用。请帮忙解决这个问题!!! 提前致谢
答案 0 :(得分:0)
很难推断当前场景的确切工作方式,例如仅在x + 20 < 50
时检查的碰撞,但问题可能在于获取getImageData的区域:x和y头像的位置&#39;宽度为10(context.getImageData(x, y, 10, 10);
)这将检查newavatar位置的左侧是否有碰撞,但不是右侧的移动方向。为此,应检查x + avatarWidth- XMovement和XMovement的宽度。
可能与您当前的设置不完全对应,但制作了一个模仿运动的fiddle。在其中检查整个头像目标位置以便更快地进行设置,但可以根据需要进行优化以使用新的重叠。
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = 100, y = 200;
var imgWidth = 50, imgHeight = 50;
var checkcollision = function(){ //checks collision of the entire 'avatar' rectangle. This can be done more efficiently by only checking the moved to area, but that would require different parameters per direction.
var data = context.getImageData(x , y, imgWidth, imgHeight).data;
return data.some(function(p){ return p != 0;});
}
function right() {
context.clearRect(0,0, canvas.width, canvas.height);
art(); //draw maze
//myImage11.src = "Point.png";
var curx= x;
x+=20;
while(checkcollision() && x > curx){ //while collision decrease x (note, this could be more efficient by just checking the new position overlap)
x--;
}
drawAvatar();
}
function art(){
context.moveTo(100,400); //decreased y a bit to keep it easier viewable while testing
context.lineTo(100,300);
context.lineTo(200,300);
context.lineTo(200,200);
context.stroke();
}
function drawAvatar(){
//context.drawImage(myImage11, x, y, imgWidth, imgHeight);
context.fillRect(x,y,imgWidth,imgHeight);
}
art();drawAvatar();
答案 1 :(得分:0)
图像数据确实做了一些奇怪的事情 有时你画的颜色有点偏。 检查y = 98,99,100之间的差异 http://jsfiddle.net/15wsszw4/
公式得到x,y
处像素的RED值console.log('R:'+imgData.data[y*4*c.width+x*4])