schteppe / cannon.js

A lightweight 3D physics engine written in JavaScript.
http://schteppe.github.com/cannon.js
MIT License
4.68k stars 710 forks source link

Acceleration #268

Open OmarAlikhan opened 8 years ago

OmarAlikhan commented 8 years ago

I'm trying to mimic an accelerometer for a simple robot simulator that I'm writing using Cannon JS. What would the easiest and ideal way be to get the acceleration of a body? Currently my robot is using the RaycastVehicle class. I would like to be able to take into consideration the acceleration caused by gravity as well.

After going through the source code, the only idea I can think of is using the F=MA formula but I'm unable to get the forces being acted on a body at any given point in time? I'm not sure if this would be the correct way of getting the acceleration either.

schteppe commented 8 years ago

Hi, You could probably use the change in body.velocity, and divide by world.dt.

Something like this?

var previousVelocity = new CANNON.Vec3();
world.addEventListener('postStep', function(){
    body.velocity.vsub(previousVelocity, acceleration); // a = v - v_old;
    acceleration.scale(1/world.dt, acceleration);  // a = a / dt
    previousVelocity.copy(body.velocity);
});