Rohan
Rohan

Reputation: 456

Stop Body Rotation in PhysicsJS

I'm looking for the best practice approach to stop PhysicsJS bodies from being able to rotate. I have tried cancelling the body's rotational velocity. Yet this does not seem effective on the step as the body still somehow sneaks in some rotation. Combining this with setting the body's rotation manually seems to work at first:

world.on('step', function(){
    obj.state.angular.pos = 0;
    obj.state.angular.vel = 0;
    world.render();
});

However in the past I have experienced a lot of bugs related to this method. Seemingly to do with the object being allowed to rotate just slightly before the step is called, which causes it to be "rotated" very quickly when its body.state.angular.pos is set back to zero. This results in objects suddenly finding themselves inside the subject, or the subject suddenly finding itself inside walls/other objects. Which as you can imagine is not a desirable situation.

I also feel like setting a body's rotation so forcefully must not be the best approach and yet I can't think of a better way. So I'm wondering if there's some method in PhysicsJS that I haven't discovered yet that basically just states "this object cannot rotate", yet still allows the body to be treated as dynamic in all other ways.

Alternatively what is the "safest" approach to gaining the desired effect, I would be happy even with a generic guide not tailored to physicsJS, just something to give me an idea on what is the general best practice for controlling dynamic body rotations in a simulation.

Thanks in advance for any advice!

Upvotes: 0

Views: 388

Answers (1)

zealoushacker
zealoushacker

Reputation: 6906

The key to accomplishing this is to ensure that you put the body to sleep first and then immediately wake it up, afterward setting the angular velocity to zero.

So for example, what I've been doing to prevent bodies that have collided from rotating was:

  world.on('collisions:detected', function(data, e) {
    var bodyA = data.collisions[0].bodyA,
        bodyB = data.collisions[0].bodyB;

    bodyA.sleep(true);
    bodyA.sleep(false);
    bodyA.state.angular.vel = 0;

    bodyB.sleep(true); 
    bodyB.sleep(false); 
    bodyB.state.angular.vel = 0;
  });

I've also seen this accomplished by increasing the mass of the bodies in question to a ridiculously high number, but this would have possible side effects that you may not desire.

Upvotes: 1

Related Questions