繁体   English   中英

检查迷宫游戏在画布中的碰撞

[英]Checking for collision for maze game in canvas

我正在尝试在画布上开发一个迷宫游戏。 我已经手动绘制了迷宫,例如

    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;
        }
    }
}

但这是行不通的。 请帮忙解决这个问题!!! 提前致谢

很难推断当前场景的确切工作原理,例如仅当x + 20 < 50时才检查冲突,但是问题可能出在从中获取getImageData的区域:“头像”的x和y位置与宽度为10( context.getImageData(x, y, 10, 10); )这将检查newavatar位置的左侧是否发生碰撞,但不检查移动方向的右侧。 为此,应检查x + avatarWidth- XMovement和XMovement的宽度。

也许并不完全适合目前设定相应的,而是做了一个小提琴模仿运动。 在其中检查了整个虚拟形象目标位置,以实现更快的设置,但如果需要,可以优化为使用新的重叠。

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();

图像数据确实有些怪异的东西有时,您绘制的颜色略有偏离。 检查y = 98,99,100之间的差异http://jsfiddle.net/15wsszw4/

该公式获取x,y处像素的RED值

console.log('R:'+imgData.data[y*4*c.width+x*4])

暂无
暂无

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

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