Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

compound body center of mass #230

Closed
WillH0lt opened this issue Sep 19, 2015 · 2 comments
Closed

compound body center of mass #230

WillH0lt opened this issue Sep 19, 2015 · 2 comments

Comments

@WillH0lt
Copy link

Thanks for the awesome physics library -- it's fast and works nicely with three.js! 馃槃 Letely I've been playing around with compound bodies using .addShape(...); like this example. It all works as expected except that, as I add shapes, the body behaves as though the center of mass is in the wrong place. It seems like it's located at the body's origin. My intention is to have the COM move as I add shapes to the body -- I'm assuming the shapes all have the same density. Is there something else I need to do?

@schteppe
Copy link
Owner

Hi,
The Body mass won't move as you add shapes - this has to be done manually.
What you have to do is computing a new COM and move the Body there, and then move all shapes the reverse distance. I made a method for this in p2.js, maybe it's easy enough to port to cannon? https://github.com/schteppe/p2.js/blob/master/src/objects/Body.js#L862

@WillH0lt
Copy link
Author

Thank you! I got it to work. My program uses voxel shapes, so it was easy enough to calculate the COM and move everything like you said.

var updateCOM = function( body ) {
    //first calculate the center of mass
    var com = new CANNON.Vec3();
    body.shapeOffsets.forEach( function( offset ) {
        com.vadd( offset, com );
    });
    com.scale( 1/body.shapes.length, com );

    //move the shapes so the body origin is at the COM
    body.shapeOffsets.forEach( function( offset ) {
        offset.vsub( com, offset );
    });

    //now move the body so the shapes' net displacement is 0
    var worldCOM = new CANNON.Vec3();
    body.vectorToWorldFrame( com, worldCOM );
    body.position.vadd( worldCOM, body.position );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants