我不希望我的“播放器”离开屏幕,我该如何防止这种情况发生?

时间:2016-03-05 15:56:47

标签: javascript html canvas keydown

这是我的JavaScript。在底部附近,您将看到针对keydown事件的addEventListener。在该函数中,keydown代码就在那里。该代码包含在if函数中,if函数中包含if,以阻止播放器离开画布。

function initCanvas() {
    var canvas = document.getElementById('my_canvas');
    var ctx = canvas.getContext('2d');
    var cW = ctx.canvas.width;
    var cH = ctx.canvas.height;
    var dist = 10;

    function Player() {
        this.x = 0, this.y = 0, this.w = 50, this.h = 50;

        this.render = function() {
            ctx.fillStyle = "orange";
            ctx.fillRect(this.x, this.y, this.w, this.h);
        }
    }

    var player = new Player();
    player.x = 100;
    player.y = 225;

    function animate() {
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        player.render();
     }
    var animateInterval = setInterval(animate, 30);

    document.addEventListener('keydown', function(event) {
        var key_press = String.fromCharCode(event.keyCode);
        if (//I don't know what should go here) {
            if (key_press == "W") {
                player.y -= dist;
            } else if (key_press == "S") {
                player.y += dist;
            } else if (key_press == "A") {
                player.x -= dist;
            } else if (key_press == "D") {
                player.x += dist;
            }
        }
    });

}

window.onload = initCanvas();

1 个答案:

答案 0 :(得分:0)

< dist

额外的检查将检查他是否位于距边缘< dist距离不在画布的边缘。 假设左上角是(0,0)。

请注意,当用户与画布距离{{1}}时,将用户移动到画布边缘会更好。我会把这个留给你。