如何在div中保持移动div

时间:2019-03-03 01:27:18

标签: javascript html

我正在做一个游戏,鼠标必须在迷宫中导航才能找到奶酪块。但是我似乎无法弄清楚如何将鼠标保持在游戏区域内,如果有人可以引导我前进,将不胜感激!

let mazeBG = document.getElementById("gamearea");
let mouse = document.getElementById("snake");
let cheese = document.getElementById("food");
let game  = 1;
let posY = 0;
let posX = 0;

document.onkeydown = function(key){
    if (key.keyCode == 38){
        posY -= 5;
        mouse.style.top = posY + "px";
    } else if (key.keyCode == 39){
        posX += 5;
        mouse.style.left = posX + "px";
    } else if (key.keyCode == 37){
        posX -= 5;
        mouse.style.left = posX + "px";
    } else if (key.keyCode == 40){
        posY += 5;
        mouse.style.top = posY + "px";
    };
};

1 个答案:

答案 0 :(得分:1)

类似这样的东西:

let mazeBG = document.getElementById("gamearea");
let mouse = document.getElementById("snake");
let cheese = document.getElementById("food");
let game  = 1;
let posY = 0;
let posX = 0;
const step = 5;

document.onkeydown = (key) => {
    if (key.keyCode == 38){
        if (posY >= step) {
          posY -= step;
          mouse.style.top = posY + "px";
        }
    } else if (key.keyCode == 39){
            if (posX <= (600 - step - 20)) { // Width of gamearea - step - width of the avatar
          posX += step;
          mouse.style.left = posX + "px";
        }
    } else if (key.keyCode == 37){
          if (posX >= step) {
          posX -= step;
          mouse.style.left = posX + "px";
        }
    } else if (key.keyCode == 40){
        if (posY <= (400 - step - 20)) { // Height of gamearea - step - height of the avatar
          posY += step;
          mouse.style.top = posY + "px";
        }
    };
};

https://jsfiddle.net/tcbnka1m/

尽管如此,我强烈建议您在制作游戏时使用画布动画。