schteppe / p2.js

JavaScript 2D physics library
Other
2.63k stars 329 forks source link

Rotating body/shape around custom body point #318

Closed TomaszSzymczak closed 6 years ago

TomaszSzymczak commented 6 years ago

Hello,

I am looking for possibility of rotating object around point other than center of mass (as I understand it's [0,0] in potential shape offset).

Our team is working on multiplayer game where you sail a ship on 2d map (camera view is from the top). So when you want to turn left, you need to rotate ship of specific angle not in its center but where the rudder blade is, so generally the back of the ship.

In Phaser, you can set object param .anchor.set( 0, 0.5 ) to gain what we want. Is it somehow possible in p2? I believe so, but could not find a way. Can You help me?

Best regards, Tom

schteppe commented 6 years ago

p2 does not really have a local anchor, the center of mass is always in the center. However, you can get the same effect by moving all the shapes relative to the center of rotation (=center of mass):

var shapeOffset = [0,-0.5]; // shape position relative to the body center of rotation
var shapeAngle = 0;
body.addShape(new p2.Box({ width: 1, height: 1 }), shapeOffset, shapeAngle);

The shape is placed 0.5 units to the left relative to the center of rotation. In other words: the center of rotation is moved 0.5 units to the right relative to the shape.

TomaszSzymczak commented 6 years ago

It works, thank You :)

Best regards, Tom