[英]I'm trying to make a game but I ran into a problem
I am trying to make a game in which your goal is to get to the end of a maze without hitting any walls, I want to make sure you can't stop moving.我正在尝试制作一款游戏,其中你的目标是在不撞到任何墙壁的情况下到达迷宫的尽头,我想确保你不能停止移动。 So when I press WI should move up and when I would press DI should stop moving up and start moving to the right.
所以当我按下 WI 时应该向上移动,当我按下 DI 时应该停止向上移动并开始向右移动。
The problem is that I can't figure out how to make sure you stop moving when you press another key.问题是我不知道如何确保您在按下另一个键时停止移动。
This is what I have now:这就是我现在所拥有的:
function moveRight() {
var moveRight = setInterval(function(){
let top =
parseInt (window.getComputedStyle(character).getPropertyValue("top"));
let left =
parseInt (window.getComputedStyle(character).getPropertyValue("left"));
left += 1;
character.style.left = left + "px";
}, 1);
}
document.addEventListener("keydown", event => {
if(event.key==="a") {moveLeft();}
if(event.key==="d") {moveRight();}
if(event.key==="s") {moveDown();}
if(event.key==="w") {moveUp();}
});
Your character continues moving because you are setting the interval and never stopping it.您的角色继续移动,因为您正在设置间隔并且从不停止它。 First you need all the references to your intervals as global variables, so define them outside function:
首先,您需要对区间的所有引用作为全局变量,因此在 function 之外定义它们:
var movingRight = false;
var movingLeft = false;
var movingUp = false;
var movingDown = false;
Then you need event listeners for both keydown and keyup然后你需要 keydown 和 keyup 的事件监听器
document.addEventListener("keydown", event => {
if(event.key==="a") {startMoveLeft();}
if(event.key==="d") {startMoveRight();}
if(event.key==="s") {startMoveDown();}
if(event.key==="w") {startMoveUp();}
});
document.addEventListener("keyup", event => {
if(event.key==="a") {stopMoveLeft();}
if(event.key==="d") {stopMoveRight();}
if(event.key==="s") {stopMoveDown();}
if(event.key==="w") {stopMoveUp();}
});
Finally create all the start and stop functions, example for Right:最后创建所有的启动和停止功能,例如 Right:
function startMoveRight() {
movingRight = setInterval(function(){
let top =
parseInt (window.getComputedStyle(character).getPropertyValue("top"));
let left =
parseInt (window.getComputedStyle(character).getPropertyValue("left"));
left += 1;
character.style.left = left + "px";
}, 1);
}
function stopMoveRight() {
clearInterval(movingRight);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.