【问题标题】:How to check if a drawn wall is touching player (canvas) for collisions?如何检查绘制的墙是否与玩家(画布)发生碰撞?
【发布时间】:2021-11-26 05:34:04
【问题描述】:

我有一个使用 canvas html 元素的 2D 地图,我画了一个红色方块作为播放器,下面是一堵浅蓝色的墙。我想知道如何检测玩家(红色方块)是否正在接触墙壁(浅蓝色)。我没有课程或任何东西,只是使用画布元素绘制了正方形,并设置了位置。

代码:

var ctx = document.getElementById("canvas").getContext('2d')
document.getElementById("canvas").tabIndex = 1;
// quick way to get focus so keypresses register
ctx.font = '8px sans';
var offsetx = 0
var offsety = 0
var things = [
    [0,100,300,50]
]

function offset() {
    ctx.save();
    ctx.translate(offsetx,offsety);
    // clear the viewport
    ctx.clearRect(-offsetx, -offsety, 300,300);
    ctx.fillStyle = "red";
    ctx.fillRect(50-offsetx,50-offsety,8,8)
    // draw the other stuff on the screen, which have the set positions in the array.
    var l = things.length;
    var i = 0;
    for (i = i; i < l; i++) {
        var x = things[i][0];
        var y = things[i][1];

        var sizex = things[i][2]
        var sizey = things[i][3]
        ctx.fillStyle = 'lightblue';
        ctx.fillRect(x, y, sizex, sizey);
        ctx.fillStyle = 'black';
    }
    ctx.restore();
}
offset(); // the first call to draw all the elements.

document.getElementById("canvas").addEventListener('keydown', function(e) {
    if (e.keyCode === 37) { // left
        offsetx++;
    } else if (e.keyCode === 39) { // right
        offsetx--;
    } else if (e.keyCode === 38) { // up
        offsety++;
    } else if (e.keyCode === 40) { // down
        offsety--;
    }
    offset();
}, false);

setInterval(function() {
    // in here i would check for the collisions
}, 10);

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    我自己想出来的,因为没有其他人会。基本上,您给绘制的墙壁(带有设置的位置)一些设置位置,用于设置阻力或碰撞点的位置。然后,在玩家移动之前,在移动功能中检查该玩家是否在墙上、之前或在那面墙上。如果是,则返回,否则继续。这是我的代码示例:

    jsfiddle.net/57xm0fw1/1/

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多