I encountered an issue while developing a pong game using html/css/javascript. Everything was going smoothly until I introduced a second setTimeout() function.
Here is the snippet of my html code:
<!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>
The css styling information is not relevant to this problem.
Here is the player.js script:
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");
The ball.js script is as follows:
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");
Finally, here is the funcs.js script:
function move() {
player.move();
ball.move();
}
function back() {
player.back();
}
After implementing both the player and ball movement functions simultaneously, the player starts behaving erratically by moving up and down rapidly, while the ball flies off the screen uncontrollably. Despite the unconventional coding approach, it worked fine individually for each element. Your guidance in resolving this issue would be greatly appreciated. Thank you!