I'm having an issue with a bouncing ball function that I created. The function displays a green bouncing ball on the screen and bounces it around. However, each time the function is called, the ball seems to pick up speed and its velocity increases dramatically.
function throwBall() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!ballState.paused) {
requestAnimationFrame(throwBall);
}
if (ballState.cx + ballRadius >= canvas.width) {
ballState.vx = -ballState.vx * damping;
ballState.cx = canvas.width - ballRadius;
} else if (ballState.cx - ballRadius <= 0) {
ballState.vx = -ballState.vx * damping;
ballState.cx = ballRadius;
}
if (ballState.cy + ballRadius + floor >= canvas.height) {
ballState.vy = -ballState.vy * damping;
ballState.cy = canvas.height - ballRadius - floor;
// traction here
ballState.vx *= traction;
} else if (ballState.cy - ballRadius <= 0) {
ballState.vy = -ballState.vy * damping;
ballState.cy = ballRadius;
}
ballState.vy += gravity;
ballState.cx += ballState.vx;
ballState.cy += ballState.vy;
ctx.beginPath();
ctx.arc(ballState.cx, ballState.cy, ballRadius, 0, 2 * Math.PI, false);
ctx.fillStyle = '#2ed851';
ctx.fill();
}
Your assistance in resolving this problem would be greatly appreciated.