schteppe / p2.js

JavaScript 2D physics library
Other
2.64k stars 330 forks source link

Don't update center of mass when adding bodies / fromPolygon? #240

Open AndrewRayCode opened 8 years ago

AndrewRayCode commented 8 years ago

I've discovered that when adding a shape to a body, and calling body.fromPolygon(), the center of mass of the object gets updated. The docs don't really mention this:

Will automatically update the mass properties and bounding radius.

However, from my perspective this is an unexpected and undesired side effect. I wouldn't inherently expect adding new shapes to a body to update the center of mass. I would expect to call updateCenterOfMass() manually if I needed to.

Let me explain my full use case. I'm creating buttons:

screen shot 2016-06-05 at 1 59 31 pm

You can see that with my green bounding cage, the center of mass is in the middle of this cube. When I create the button p2 box for collision, I place it relative to the center of that green bounding cage, as in cage.y + 0.5; My mental model was that I could then simply rotate the body if I need a sideways button:

screen shot 2016-06-05 at 2 01 38 pm

because I assumed the pivot point would be unchanged. However, because the center of mass was updated, it's now the middle of the button hitbox, not the middle of the green bounding cage. So instead of rotating how I'd expect around a pivot point, it rotated in place and took some debugging to figure out.

I don't know if this change would be too breaking to include in the library, or if it conflicts with your motivations for setting up this API. Just sharing my perspective that it would have saved me some time debugging, and from an API view I would consider this a "side effect" of adding a shape, which I don't think should be automatic.

schteppe commented 8 years ago

Everything you say about this is perfectly sane. This will align the behavior with .addShape() as well. Care to make a PR?

sbj42 commented 7 years ago

I agree with OP for static objects, but for dynamic ones the object might appear to act funny if its center of mass isn't the centroid of the shape.

If you want to rotate the body around something other than its center of mass then you need to adjust the body's position accordingly. That's not super trivial code to write, so as an alternative to changing fromPolygon's behavior, you might consider just a helper function for rotating a body around a point other than it's center of mass.