Acting like a god with Physics

In physics, we are supposed to let forces move physics bodies. In some cases like dragging or attach we use a joint to connect the physics body with a non-physics body like the mouse or a ZIM object.

We also provide x, y and rotation as convenience properties of the physics body and these, for x and y, called the Box2D SetPosition() method which takes in two vectors for x and y that need to be converted to meters which Box2D uses as dimensions.

We just realized that if we set one of either x or y then the other was not necessarily correct - it used an old value. When we tried to correct this and then tried setting both x and y, only the last one set would work due to a delay in the physics. The only solution seems to be to set both at the same time with SetPosition().

So we wrapped SetPosition() in a new method on the body that does the conversion. The new method is called loc(). It also applies a little little force to wake the body up after setting the new position. The IsAwake() and IsActive() methods did not seem to do it. So x and y on the body have been deprecated.

new Physics().drag();
const ball = new Circle().center().addPhysics();
timeout(3, ()=>{ball.body.loc(200,200);});

From now on, we recommend using zimObj.body.loc(x,y) any time you need to manually set position. Note that this is on the ZIM object's body. It is not the zimObj.loc() method as that will not work - nor will setting the ZIM object's x, y, pos, center, centerReg. Those things only work BEFORE adding physics.

Also, you may want to remove any existing forces or rotation. To do that use methods of the ZIM object:

ball.setLinearVelocity(0,0).setAngularVelocity(0);
3 Likes

Thanks!
That on ZIM 16?

Yes - it has loc() on the zimObj.body has been added. The others things were there already.