问题描述
我现在只学习JavaScript 4天,我想创建吃豆人:D。
现在我的吃豆人(目前仅是一个按钮)应该每100毫秒移动2个像素,但是在1秒内只能移动20个像素。
在我的脚本中有两个setInterval()
嵌套。也许这就是问题
有人可以帮助我吗?预先感谢!
无论如何,这是我的代码:
<html lang="de">
<head>
<title>Pac Man</title>
<Meta charset="UTF-8">
<style>
#pacman {
margin: 10px;
top: 0;
position: absolute;
}
td {
background-color: green;
height: 50px;
width: 50px;
}
table {
border-spacing: 0;
margin: 200px;
}
td.wall {
background-color: darkgreen;
}
</style>
<script>
walls = document.querySelectorAll(".wall");
positionX = 10;
positionY = 10;
movingX = 0;
movingY = 0;
document.addEventListener("keydown",function(event) {
if (event.keyCode == 87) { // W
movingX = 0;
movingY = -2;
}
if (event.keyCode == 83) { // S
movingX = 0;
movingY = 2;
}
if (event.keyCode == 65) { // A
movingX = -2;
movingY = 0;
}
if (event.keyCode == 68) { // D
movingX = 2;
movingY = 0;
}
if (event.keyCode == 27) { // ESCAPE
movingX = 0;
movingY = 0;
}
});
</script>
</head>
<body>
<table>
<tr>
<td class="wall">
</td>
<td>
</td>
<td class="wall">
</td>
</tr>
<tr>
<td>
</td>
<td class="wall">
</td>
</tr>
</table>
<button id="pacman">Top</button>
</body>
<script>
let walls = document.querySelectorAll(".wall");
setInterval(function() {
checkAndMove();
},1000);
function checkAndMove() {
if (checkWalls() == 1) {
for (i = 0; i < 10; i++){
setTimeout(function() {
move();
},100);
}
}
}
function checkWalls() {
for (i = 0; i < walls.length; i++) {
rect = walls[i].getBoundingClientRect();
if ((positionX + (movingX * 30)) > rect.left &&
(positionX + (movingX * 30)) < rect.right &&
(positionY + (movingY * 30)) > rect.top &&
(positionY + (movingY * 30)) < rect.bottom) {
return false;
}
}
return 1;
}
function move() {
document.getElementById("pacman").style.marginTop = (positionY += movingY) + "px";
document.getElementById("pacman").style.marginLeft = (positionX += movingX) + "px";
}
</script>
</html>```
解决方法
您在100 * i
中缺少checkAndMove
。
通过添加100 * i
,setTimeout
的设置间隔为100ms:0ms,100ms,200ms,300ms,400ms,500ms,600ms,700ms,800ms和900ms。
function checkAndMove() {
if (checkWalls() == 1) {
for (i = 0; i < 10; i++) {
setTimeout(function() {
move();
},100 * i); // 100 * i added here
}
}
}
不过,我建议将setTimeout
放在setInterval
之外。您可以有一个setInterval
,每个100ms
都运行,而move()
也可以运行。有更高级的方法可以做到这一点,但是如果您正在尝试,我相信现在就足够了。