javascript - 使用两个 setTimeout 函数后图像变得疯狂

标签 javascript html css

我正在使用 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 函数使球移动。当我只调用它时它工作正常。但是当我叫他们两个时,球员会发疯,上下移动非常快,而球刚好飞出屏幕。我的编码可能看起来有点奇怪,但我在写作时遇到了其他一些问题,这种写作方式很有效。

非常感谢您的帮助,谢谢。

最佳答案

如果您在控制台中暂停脚本执行并将鼠标悬停在 BallPlayer 函数中使用的 this.move 上,您将看到 this.move 指的是:

function move() {
    player.move();
    ball.move();
}

这意味着每次在 PlayerBall 中调用 this.move 时,它都会在 中再调用两次code>player.move()ball.move()

关于javascript - 使用两个 setTimeout 函数后图像变得疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642409/

相关文章:

javascript - 如何通过 iphone html 像电话号码一样使地址可点击(可检测)?

javascript - 如何通过分页更改 Bootstrap 选项卡

html - 如何让字体光标位于顶部,文本对齐: top?

jquery - 在 BlackNegative - "What' s Hot 页面上看到的效果

html - 绝对定位的 DIV 内部的 SVG 绘图区域缩小

html - 当彼此相邻显示为内联 block 时,CSS 会向上移动内容

javascript - 一次将事件句柄附加到多个元素

javascript - Highcharts - 悬停时 x 坐标之间的不同填充颜色

javascript - 如何在不向DOM呈现任何内容的情况下计算文本高度?

Javascript 异常(仅发生在 PC 上的 FireFox 4.01 中)