saharan / OimoPhysics

A cross-platform 3D physics engine
MIT License
863 stars 68 forks source link

Move a body with local coordinates #10

Closed anemol closed 6 years ago

anemol commented 6 years ago

If I apply a force with applyImpulse or linearVelocity to x on an object, it moves relative to the global coordinates. I would like it to move relative to its local coordinates (so depending on its rotation).

How to do?

saharan commented 6 years ago

You can use RigidBody.getWorldVector to transform a vector from local space to global space. To apply an unit linear force along the x axis of a rigid body r, the following code can be used:

var localForce = new Vec3(1, 0, 0);
var globalForce = r.getWorldVector(localForce);
r.applyForceToCenter(globalForce);

hope it helps :)

anemol commented 6 years ago

Thanks for help. :) Unfortunately, i use oimo for nodejs (https://github.com/lo-th/Oimo.js/) and these functions aren't available. I thought i could use the same functions, but the project must be obsolete. I will check if it is possible to export for nodejs module.

saharan commented 6 years ago

Oh I see, then it would be easier to rotate a vector by yourself. A rotation matrix of a rigid body represents a transform from its local space to the global space. So you can obtain a vector in the global space by simply multiplying the rotation matrix to a vector in the local space. the following pseudocode shows the way to do it.

let localForce = Vec3(1, 0, 0)
let rotMatrix = r.rotationMatrix
let globalForce = rotMatrix * localForce // an appropriate method should be called in js
r.applyForceToCenter(globalForce)