我正在使用 html/css/javascript 制作乒乓球游戏,一切顺利,直到我添加了第二个 setTimeout()
这是我的html代码
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="player.js"></script>
<script type='text/javascript' src="ball.js"></script>
<script type='text/javascript' src="funcs.js"></script>
<link rel="stylesheet" type="text/css" href="cetrnes.css"/>
</head>
<body>
<img src="universe-54a.jpg" width="700px" height="525px" onclick="back()"></img>
<img id="player" src="player1.png" onload="move()"></img>
<img id="ball" src="ball.png"></img>
</body>
</html>
CSS 无关紧要。
player.js 脚本:
function Player(ID) {
this.t;
this.y = 170;
this.speed = -3;
this.move = function move() {
if (this.y > 1 && this.y < 421) {
this.y += this.speed;
}
else if (this.y < 1) {
this.y = 2;
this.speed = 3;
}
else {
this.y = 420;
this.speed = -3;
}
document.getElementById(ID).style.top=this.y + "px";
this.t = setTimeout("this.move()",10);
}
this.back = function back() {
if (this.speed < 0)
this.speed = 3;
else
this.speed = -3;
}
}
var player = new Player("player");
ball.js 脚本:
function Ball(ID) {
this.t;
this.x = 350;
this.y = 260;
this.left = true;
this.bot = true;
this.acc = 5;
this.move = function move() {
if (this.bot)
this.y -= 3;
else if (!this.bot)
this.y += 3;
if (this.left)
this.x -= 3;
else if (!this.left)
this.x += 3;
document.getElementById(ID).style.top = this.y + "px";
document.getElementById(ID).style.left = this.x + "px";
this.t = setTimeout("this.move()",10);
}
}
var ball = new Ball("ball");
还有 funcs.js 脚本:
function move() {
player.move();
ball.move();
}
function back() {
player.back();
}
player.js 中的 move 函数让玩家上下移动,back 函数让它改变方向。当我只调用它时它工作正常。 ball.js 中的 move 函数使球移动。当我只调用它时它工作正常。但是当我叫他们两个时,球员会发疯,上下移动非常快,而球刚好飞出屏幕。我的编码可能看起来有点奇怪,但我在写作时遇到了其他一些问题,这种写作方式很有效。
非常感谢您的帮助,谢谢。
最佳答案
如果您在控制台中暂停脚本执行并将鼠标悬停在 Ball
或 Player
函数中使用的 this.move
上,您将看到 this.move
指的是:
function move() {
player.move();
ball.move();
}
这意味着每次在 Player
或 Ball
中调用 this.move
时,它都会在 中再调用两次code>player.move()
和 ball.move()
。
关于javascript - 使用两个 setTimeout 函数后图像变得疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642409/