Milos Dacic Milos Dacic - 2 months ago 11
CSS Question

Ball stops bouncing after 4-5 seconds

Here is the javascript:



var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
ax = 50,
ay = 50,
avx = 5,
avy = 2,
radius = 50;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function drawArc() {
ctx.beginPath();
ctx.fillStyle = "white";
ctx.arc(ax, ay, radius, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
};

function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawArc();
ax += avx;
ay -= avy;
avy -= 0.2;

if (ay + radius >= canvas.height) {
avy *= -0.8;
avx *= 0.9;
};

if (ax + radius >= canvas.width) {
avx = -avx;
};

if (ax - radius <= 0) {
avx = -avx;
};
}
setInterval(update, 10);

body, html {
margin: 0;
padding: 0;
}
#canvas {
background-color: black;
}

<canvas id="canvas"></canvas>





Here at Jsfiddle: https://jsfiddle.net/milosdacic/qh1ha085/

I don't know why this is happening, code seems fine.

I have done this thing before but now it won't work.

Any help will be appreciated.

Answer

Short answer is you are getting many hits because you are not moving the ball up away from the ground. The next frame it is still impacting the ground and as you reduce its speed it just bogs down..

Add this after line 29 of your fiddle.

ay = canvas.height - radius;

For more on bouncing a ball