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?