Ball Bounce Component

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.

Answer №1

Upon repeated use of this function, the ball starts to accelerate significantly with each call, resulting in a drastic increase in speed.

The issue lies within this block of code:

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

When you call this function, it continues to invoke itself for every frame using

requestAnimationFrame(throwBall);
. Subsequently calling the function again leads to multiple instances of throwBall being executed per frame, causing the position and velocity to update multiple times. This can result in an unintended speed increase.

To address this, it is advisable to separate the rendering and updating functions from the event-related animations. The current function mainly updates the ball's properties and renders it but lacks the actual 'throwing' action.

Rename the function as follows:

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

Call this function only once after initializing the canvas:

updateAndDrawBall();

To simulate throwing the ball, simply adjust its velocity and let updateAndDrawBall handle these changes during rendering:

function throwBall() {
  ballState.vx = 10
  ballState.vy = -10
}

Invoke this function whenever you want to give the ball a push, without worrying about increasing speed unintentionally.

Check out the working example below:

// JavaScript code snippet will be provided here.
// HTML code snippet will also be included.

View Typescript example on Code Sandbox

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error code TS5055 when attempting to call an API within a TypeScript constructor

I'm attempting to retrieve a list of customers by calling a GET API from a dashboard constructor as shown below: // tslint:disable-next-line:max-line-length constructor(public addCustomerDialog: MatDialog, private router: Router, private rout ...

Ensuring that the app closes completely before launching a new instance with webpack hot module reload

My nest.js application is utilizing webpack hot module reload (hmr), but I am encountering an issue where the reload does not allow the old instance to fully close (including the database connection and telegram bot) before launching a new instance. This c ...

Ways to retrieve the name of the chosen option from a dropdown menu

Is there a way to retrieve the text name of a selected dropdown value using a PrimeNG dropdown? Incorporating a PrimeNG dropdown: HTML <p-dropdown [options]="regionSelectList" [(ngModel)]="reg" [filter]="true" [ngModelOptions]="{standalone: true}"> ...

Achieve the capability to upload multiple files in Next.js using the upload.io integration feature

I'm currently using upload.io for uploads and replicate.com for an AI model on a specific app. I am able to upload one picture, but unfortunately, I am encountering issues when trying to upload multiple pictures. Can anyone identify the problem here? ...

Use the IONIC CAPACITOR application to send a 20-byte command to a BLE device

Hello everyone, I am currently working on an application that is designed to connect to a BLE device. I have a requirement to write 20 Bytes to the device using BleClient.write function. 34h 01h 50h 4Fh 4Ch 49h 54h 45h 43h 00 00 00h 00h 00h 00h 00h 00h 00h ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

What is the best way to calculate the total sum of dynamically changing inputs in Angular 2?

Is there a way to calculate the total sum from dynamic inputs in angular 2? I'm not sure how to implement this. Thanks! https://i.sstatic.net/eXBjN.png //html component <md-input-container style="width: 80px;"> <input md-inp ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

Enhancing IntelliSense to recognize exports specified in package.json

I have a package.json file where I define various scripts to be exported using the exports field. "exports": { ".": { "default": "./dist/main.es.js", "require": "./dist/main.cjs.js", ...

What is the best way to retrieve a specific property from an array of objects in Angular 6 using typescript?

I am currently working on a budgeting application that incorporates an array of expenses with a price property. Each expense is defined within an Expense model in Typescript. While I can easily access the price property using ngFor loop in HTML, I'm c ...

Incorporating lodash in a project with TypeScript and jspm

I seem to be missing something in my setup and would appreciate any assistance. I am working with TypeScript 2 + JSPM. I have tried various configurations in tsconfig using typeRoots and types (including adding the version number in the type name). Despite ...

What steps should be taken in order to resolve the error message "Type is missing an index signature"?

Is there a solution to this type error? The argument of type 'Query' is causing an issue as it cannot be assigned to the parameter of type 'Input'. This is due to the absence of an index signature in type 'Query'.(2345) In ...

Incorporating TypeScript into a React-Native Expo development venture

While attempting to integrate TypeScript into a React-Native Expo project, I encountered an error when renaming a file from abc.js to abc.tsx: I have been following the instructions provided at: https://facebook.github.io/react-native/blog/2018/05/07/u ...

Typescript compiler: Unable to locate the definition for 'Map' data type

I am developing an Electron + Angular application. I have decided to incorporate Typescript for my Electron component, so I created a main.ts file and attempted to compile it to main.js using the 'tsc main.ts' command. Unfortunately, I encountere ...

The distribution of intersection types is not properly handled by Typescript's array.map function

My array is of type object[] & Tree[], but when using arr.map(child => ...), the type of child is inferred as object instead of object & Tree. Is there a way to avoid this without additional casting? It's worth noting that Tree extends ob ...

TypeScript encountered an error (TS2403) stating that subsequent variable declarations must have matching types

Encountered an issue with my typings.d.ts file Error TS2403: Subsequent variable declarations must have the same type. Variable 'module' is expected to be of type 'NodeModule', but is currently of type '{id:string}'. declare ...

Tips for utilizing array.items in joiful validation?

Can someone provide an example code or a link on how to correctly use the joyful validation for array items? I attempted the array.items validation code using joyful, but I am not sure how to specify the items. Thanks in advance! ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...