schteppe / p2.js

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

Body coordinate system: Position vs. Center of Mass #234

Closed gaufqwi closed 8 years ago

gaufqwi commented 8 years ago

Two related questions:

Do the .position coordinates of a body necessarily refer to its center of mass?

When you do body.addShape with the optional offset argument, what point is the offset relative to? Is it the .position of the body, the body's center of mass, or possibly some other point?

schteppe commented 8 years ago

Yes, .position is always the center of mass.

From the docs:

Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and angle relative to the body center of mass.

https://github.com/schteppe/p2.js/blob/34cab31a019c30cbdac9372c943fbdb0b81b1758/src/objects/Body.js#L582

gaufqwi commented 8 years ago

I'm still confused about how the coordinate systems work. If I start with a body at world coordinates (0,0) and add a square with coordinates (-1,-1) (-1,1) (1,1) (1,-1) then the center of mass is at (0,0). If I then add another square with those same coordinates but with offset (2,0), shouldn't the center of mass now be at (1,0)? But that doesn't seem to how addShape works.

schteppe commented 8 years ago

Oh I see now.

The center off mass would indeed move if you assume even density distribution. You can even make the CM move if you run the .adjustCenterOfMass() method: http://schteppe.github.io/p2.js/docs/classes/Body.html#method_adjustCenterOfMass

However, the default behavior is to let the user set the center of mass manually. This is useful for many things. For example you can construct a car that has its CM near the ground, or an axe that has most of its mass in the metal top part.

.addShape() will only add some geometry at a position relative to the CM. It doesn't care about density or mass.

gaufqwi commented 8 years ago

Ok, thanks. Here's another question: Do you have to take the body's own angle into account when adding shapes? In other words, if I want to add a shape to the "top" of a body (from a body centric perspective), can I always used an offset like [0,y] or do I need to use the body's angle and do the trig?

schteppe commented 8 years ago

Like other physics engines, p2 shapes have a local transform inside the body. So yes, to add a shape on a world coordinate, you need to convert this coordinate to local body coords. You can use Body#toLocalFrame to do this. The corresponding local angle would be worldShapeAngle - bodyAngle.