I'm trying to make a pong game. I want to add a trail effect when the ball moves. But I couldn't figure out how to do it. This is the CSS of ball.
ball: {
width: 15,
height: 15,
position: 'absolute',
top: 0,
left: 0,
borderRadius: 50,
background: '#C6A62F'
}
I'm controlling the ball's motion in a loop called function loop(). When I create another ball inside the function, there is a trail effect but it never ends. How can I prevent from this?
function loop() {
window.pongLoop = setInterval(function () {
$('<div/>', {id: 'pong-ball'}).css(CSS.ball).appendTo('#pong-game');
CSS.stick1.top += CONSTS.stick1Speed;
$('#stick-1').css('top', CSS.stick1.top);
CSS.stick2.top += CONSTS.stick2Speed;
$('#stick-2').css('top', CSS.stick2.top);
CSS.ball.top += CONSTS.ballTopSpeed;
CSS.ball.left += CONSTS.ballLeftSpeed;
if ( CSS.stick1.top <= 1) {
CSS.stick1.top = 1;
}
if ( CSS.stick2.top <= 1) {
CSS.stick2.top = 1;
}
if (CSS.stick1.top >= CSS.arena.height - CSS.stick.height) {
CSS.stick1.top = CSS.arena.height - CSS.stick.height;
}
if (CSS.stick2.top >= CSS.arena.height - CSS.stick.height) {
CSS.stick2.top = CSS.arena.height - CSS.stick.height;
}
if (CSS.ball.top <= 0 ||
CSS.ball.top >= CSS.arena.height - CSS.ball.height) {
CONSTS.ballTopSpeed = CONSTS.ballTopSpeed * -1;
}
$('#pong-ball').css({top: CSS.ball.top,left: CSS.ball.left});
if (CSS.ball.left <= CSS.stick.width) {
if (CSS.ball.top > CSS.stick1.top && CSS.ball.top < CSS.stick1.top + CSS.stick.height) {
CONSTS.ballLeftSpeed = CONSTS.ballLeftSpeed * -1;
} else {
localStorage.setItem("Player2", JSON.stringify(parseInt(localStorage.getItem("Player2")) + 5));
$('#score-player2').text(parseInt(localStorage.getItem("Player2")));
roll();
}
}
if (CSS.ball.left >= CSS.arena.width - CSS.ball.width - CSS.stick.width) {
if (CSS.ball.top > CSS.stick2.top && CSS.ball.top < CSS.stick2.top + CSS.stick.height) {
CONSTS.ballLeftSpeed = CONSTS.ballLeftSpeed * -1;
} else {
localStorage.setItem("Player1", JSON.stringify(parseInt(localStorage.getItem("Player1")) + 5));
$('#score-player1').text(parseInt(localStorage.getItem("Player1")));
roll();
}
}
}, CONSTS.gameSpeed);
}