Calculating velocity and displacement with a specific acceleration in JavaScript: A step-by-step guide

I am faced with a challenge involving a JSON file containing acceleration values in m/s^2 along with timestamps. On the other hand, I have a ThreeJS mesh that needs to translate and rotate based on input values. My goal is to pass velocity and displacement data to the mesh for smooth acceleration and deceleration effects during rendering. I have been calculating velocity and displacement and storing them in an array, but for a real-time setup, I need to avoid memory overload by only considering the last acceleration reading. While I attempted to implement a formula for this purpose, it did not yield the expected results.

const previousVelocity = initialVelocity + ((currentAcceleration + previousAcceleration)/2)*(currentTime - previousTime)

const currentVelocity  = previousVelocity + ((currentAcceleration + previousAcceleration)/2)*(currentTime - previousTime)

const disp             = initialDisplacement + ((previousVelocity + currentVelocity)/2)*(currentTime - previousTime)

Below is an example snippet from my JSON file:

[
    {
        "time": 0,
        "acc": 0.11,
        "vel": 0,
        "disp": 0
    },
    {
       ...
]

In my render function, I access the acceleration as follows:

While I pre-calculated velocity and displacement in Excel before adding them to the JSON file, my ideal approach is to directly use the acceleration values and integrate the formula in JS without the need for an array.

function render(dt) {
    dt *= 0.8 // in seconds
    time += dt
    while (data[currentIndex].time < time) {
        currentIndex++
        if (currentIndex >= data.length) return
    }
    console.log(currentIndex);
    const {acc, vel, disp} = data[currentIndex]

    document.querySelector("#disp").textContent = disp.toFixed(2);
    object.position.y = disp*0.07; 

    var relativeCameraOffset = new THREE.Vector3 (5,0,0); 
    var cameraOffset = relativeCameraOffset.applyMatrix4( object.matrixWorld );
    camera.position.x = cameraOffset.x;
    ...

    resizeToClient();
    renderer.render(scene, camera);
    requestAnimationFrame(render);
}

How can I effectively implement this logic in JavaScript?

Answer №1

Acceleration is typically calculated from the combination of force and mass. If we assume that the force is represented by an instance of THREE.Vector3, then acceleration can be determined as follows:

acceleration.copy( force ).divideScalar( mass );

It's important to note that acceleration is also an instance of THREE.Vector3 because force is a vector quantity, possessing both magnitude and direction.

Once you have the acceleration, you can then calculate the velocity with the following equation:

velocity.add( acceleration.multiplyScalar( delta ) );

Over time, the velocity is adjusted based on the acceleration. As this calculation is done per simulation step, it's crucial to factor in the amount of acceleration over a specific timeframe (hence utilizing the time delta value).

In the subsequent stage, the displacement vector is computed and later added to the position of the 3D object:

displacement.copy( velocity ).multiplyScalar( delta );
object.position.copy( displacement );

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

I'm curious about where to find more information on this new technology called the 'scroll to page' feature

Recently, I came across a captivating website feature that caught my eye. As someone relatively new to front end web development, I am intrigued by the scrolling technique used on this site. I'm specifically drawn to the 'page to page' scro ...

A guide to creating a dynamic ngTemplateOutlet in Angular

Below is the HTML code I attempted: HTML <ng-container [ngTemplateOutlet]="room"></ng-container> <ng-template #room1> test 1 </ng-template> <ng-template #room2> test 2 </ng-template> <ng-template # ...

The watch function was triggered for a different key in the array from the one that

What is the best way to limit the watch function to only trigger for the selected key in the data array? import { useSessionStorage } from "@vueuse/core"; const defaultState = { data: [ { key: 1, name: "A" }, { key: 2, nam ...

Using React's state to hide a div reveals the div with a flicker when saving the information

Is there a way to create a hidden div that the user can show with a button in React Next.js without it flashing on reload? const [showBanner, setShowBanner] = useState(true); useEffect(() => { const data = window.localStorage.getItem('STATE& ...

Guide to showing a preview of an image prior to submitting a form using vue.js

I created a Vue form but I'm having trouble making the image preview function work when users try to submit an image to the form. After refreshing the page, I can see the image, but when uploading it, the preview link is broken. There is an option to ...

Leveraging Vue.js's capabilities with an external setup file

Is it feasible for a Vue App to access an external configuration file? I envision a setup where I deploy the application along with the config file; then, I should be able to modify the configuration in the external file without needing to rebuild the enti ...

Is it possible to alter the state of one page by clicking a link on another page?

Is it possible to update the state of a different page when a link is clicked and the user navigates to that page? For example: Homepage <Link href="/about"> <button>Click here for the About page</button> </Link> If a ...

Transform the data into put and choose the desired item

Here is the data I am working with "dates": { "contract": [ {"id":1,"name":"1 month","value":false}, {"id":2,"name":"2 months","value":true} ] } I want to display this data in a select dropdown on my HTML page. Here is what I have tried s ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

Guide to successfully merging Mysql data with PHP into the ParamQuery Grid using Javascript

Could you please assist in converting the JSON output from MySQL into the desired format shown below? JSON [ {"storenm": "S1", "FA_SOH": "20964", "FA_CY_QTY": "15", "FA_CT_QTY": "44497"}, {"storenm": "S2", "FA_SOH": "1096", "FA_CY_QTY": "2", "FA_ ...

Tips on utilizing Jquery to extract an array containing UL, LI, and input elements

I am currently working with five ul lists, each of which may contain an input element. For example: <form id="testForm"> <ul id="1"> <li>TEST</li> <li>Gender: <select id="gender" name="gender"> ...

What is the connection between {{result}} and $scope.result within AngularJS?

I comprehend the concept of binding a model to an element. An example would be... <pre ng-model="result">. This connection is established through the $scope.result variable. However, how are these two related? {{result}} $scope.result = data; ...

JavaScript: Break apart and tally the number of words within a given string

If I have an input string with the value "testing the string", I want to create a function that splits each word and counts how many times each word appears in the input string. The desired output should look like this: testing: 1, the: 1, string: 1 Than ...

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

What steps can I take to resolve the error message "TypeError: url.lastIndexOf is not a function" in three.js?

I am currently experimenting with loading a gLTF file in Three.js r105. After successfully loading the file, I decided to try changing the URL post-loading to see if it was possible. However, this decision led me straight into a problem. Initially, I atte ...

What is the best way to convert a requested JSON array into a CSV file using Python?

I'm completely new to programming and I'm having trouble saving my data. Currently, I'm working on a website for a scientific experiment where users are required to click 'yes' or 'no' buttons to indicate their recognitio ...

Implement a versatile Bootstrap 5 carousel featuring numerous sliders

Is it possible to create a Bootstrap 5 carousel with six items displaying at a time instead of three? I tried changing the value in the JS code, but it didn't work. Can you correct my code so that it displays six items at a time and can be variable la ...

What could be hindering my jQuery function from running the Ajax script?

My jQuery function is supposed to retrieve two values, one for school/college and one for state, and send it to the controller class under the URL "Type&State". However, for some reason, the data is not being passed and nothing is shown in the console ...

Using values from a preexisting array to generate new arrays in JavaScript

I'm currently facing a challenge in JavaScript where I need to generate arrays based on the values of another array. For instance, I have an array of dates in string format (dates) listed below: ["30/09/2015", "31/10/2015", "30/11/2015", "31/12/2015 ...

Implementing a method for JQuery event handlers to access variables within a module pattern

var MODULE = (function() { var app = { hi: "hi dad", // How can I retrieve this value? onSubmitClick: function() { $('button').click(function() { console.log(hi); // Is there a way to access ...