Javascript - 基于颜色的在线碰撞检测

Javascript - Online collision detection based on colours

我的游戏是 colegame.herokuapp.com,我想知道我是否可以做到这样就不可能离开 canvas,因为如果他们离开 canvas,你就看不到任何人。对于我的玩家,我使用表情符号来简化编码并减少耗时。有谁知道如何根据颜色进行碰撞检测?谢谢,请提供用于它的代码,因为我是初学者。我的 canvas 的大小取决于屏幕的大小。虽然它总是一个正方形。

您需要根据 canvas 的大小来限制播放器的位置。

这是一个 100x100 世界的示例,其中有一个 10x10 玩家。

点击黑框,使用键盘方向键移动 "player"。

var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");
var playerPosition = [45, 45];

if (canvas.getContext) {
    draw();
    window.addEventListener('keydown', move, true);
}

function move(evt)
{
    switch (evt.keyCode) {
        case 37: // left
            playerPosition[0] -= 5;
            break;
        case 38: // up
            playerPosition[1] -= 5;
            break;
        case 39: // right
            playerPosition[0] += 5;
            break;
        case 40: // down
            playerPosition[1] += 5;
            break;
    }
    
    // restricting the movement of the player happens here
    if (playerPosition[0] < 0) playerPosition[0] = 0;
    if (playerPosition[0] > 90) playerPosition[0] = 90;
    if (playerPosition[1] < 0) playerPosition[1] = 0;
    if (playerPosition[1] > 90) playerPosition[1] = 90;
    
    draw();
}

function draw() {
    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, 100, 100);
    ctx.fillStyle = "#ff0000";
    ctx.fillRect(playerPosition[0], playerPosition[1], 10, 10);
}
#my-canvas {
  width: 100px;
  height: 100px;
}
<canvas id="my-canvas"></canvas>