Skip to content

Commit

Permalink
Merge pull request #167 from sakatam/master
Browse files Browse the repository at this point in the history
Throttling frame rate for consistent ball animation
  • Loading branch information
tonybaloney authored Oct 1, 2022
2 parents b94eabb + 3734a0a commit a944134
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/panel/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,22 +268,33 @@ export function petPanelApp(
}

/// Bouncing ball components, credit https://stackoverflow.com/a/29982343
const gravity: number = 0.2,
const gravity: number = 0.6,
damping: number = 0.9,
traction: number = 0.8;
traction: number = 0.8,
interval: number = 1000 / 24; // msec for single frame
let then: number = 0; // last draw
var ballState: BallState;

function resetBall() {
canvas.style.display = 'block';
ballState = new BallState(100, 100, 2, 5);
ballState = new BallState(100, 100, 4, 5);
}

function throwBall() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!ballState.paused) {
requestAnimationFrame(throwBall);
}

// throttling the frame rate
const now = Date.now();
const elapsed = now - then;
if (elapsed <= interval) {
return;
}
then = now - (elapsed % interval);

ctx.clearRect(0, 0, canvas.width, canvas.height);

if (ballState.cx + ballRadius >= canvas.width) {
ballState.vx = -ballState.vx * damping;
ballState.cx = canvas.width - ballRadius;
Expand Down

0 comments on commit a944134

Please sign in to comment.