Search code examples
physicsjs

Move a body by changing its position using PhysicsJS


I was able to move a body to an specific point by changing its state.pos AND its state.old.pos. But it seems to lose its velocity (and acceleration I suppose).

Doing it like this:

ship.body.state.pos.x = -context.width / 2 - ship.radius;
ship.body.state.old.pos.x = -context.width / 2 - ship.radius;

Is there a better way to do it? How can I change its position and keep everything else the same?

Is there something about it in the documentation? I was unable to find it.


Solution

  • I found a solution. I did not went through all the source but having some previous experience with Physicsjs integrators (https://coderwall.com/p/ntb6bg/metres-seconds-and-newtons-in-physicsjs) I started thinking they might be the root of my problem.

    So, apparently a verlet integrator is the default for Physicsjs simulations. I have used it before and it is great. But the verlet integrator uses previous position to calculate next position (no just position, it is a little more complicated than that), so changing it manually screw things up. THAT I do not know how to "fix", or if it is even possible. But there is another way.

    In my case what I have is a plain newtonian simulation without fancy stuff or crazy values (I am using the technical terms here...) so an euler integrator worked just fine and as it does not uses previous position to calculate the next it is perfect to "teletransport" my objects without losing velocity, direction etc.

    Just remember to load the integrator:

    void function (define) { 'use strict'; define( [ 'physicsjs', 'physicsjs/behaviors/attractor', 'physicsjs/behaviors/body-collision-detection', 'physicsjs/behaviors/sweep-prune', 'physicsjs/bodies/circle', 'physicsjs/integrators/improved-euler' ], physicsModule ); // function physicsModule(physics) { return physics; } }(define);

    And remember to add the integrator to the simulation:

    void function (define) { 'use strict'; define( [ 'physics' ], simulationModule ); // function simulationModule(physics) { var simulation = physics(); simulation.add(physics.behavior('body-collision-detection')); simulation.add(physics.behavior('sweep-prune')); simulation.add(physics.integrator('improved-euler')); return simulation; } }(define);