Page 1 of 1

[solved] Strange bodies behaviour

Posted: Mon Dec 20, 2010 4:01 am
by shybovycha
Greetings. I've made a simple demo application which allows user to create his own rigid bodies. But when i create a new body and it falls down to the "ground", some forces are applied to this body (and i add just gravity one though) and one start flying around almost randomly. Video and source code are avaliable at ge.tt.

Re: Strange bodies behaviour

Posted: Mon Dec 20, 2010 9:15 am
by slembcke
It looks like the center of gravity of the bodies are not actually at the shape center so the CoG is swinging somewhere down below the shapes. (0,0) in the shape coordinates is where it attaches to the center of gravity of the rigid body. Chipmunk 5.3.3 has some new utility functions for helping calculate polygon centroids and recenter polygons. Look at the end of this section: http://files.slembcke.net/chipmunk/rele ... s/#cpShape

Re: Strange bodies behaviour

Posted: Thu Dec 23, 2010 9:43 am
by shybovycha
So, now i can calculate my bodies' centroids. And gravity will still be applied to the (0,0) point, isn't it? =) So, the question is: what's the point of your answer / centroid calculation? =)

Re: Strange bodies behaviour

Posted: Thu Dec 23, 2010 10:11 am
by slembcke
No, it's changing the shape so it attaches to the body at the shape's center.

I think your problem is that you are leaving the body at (0,0), then creating the shape in world coordinates. Instead, you should be creating the body where you want the object, and make the shape relative to that.

Re: Strange bodies behaviour

Posted: Fri Dec 24, 2010 2:35 pm
by shybovycha
Here's my code for your method (if i got your idea right):

Code: Select all

cpVect center = cpCentroidForPoly(i + 1, verts);
cpBody* mybody = cpSpaceAddBody(space, cpBodyNew(100.0f, cpMomentForPoly(1.0f, i + 1, verts, cpvzero)));
mybody->p = center;
cpShape *myshape = cpSpaceAddShape(space, cpPolyShapeNew(mybody, i + 1, verts, cpvzero)); 
Anyway, this is not a working-right one =)

Re: Strange bodies behaviour

Posted: Fri Dec 24, 2010 5:10 pm
by slembcke
You are setting the CoG of the body (in absolute coords) to the centroid of the poly which is expressed in local coordinates (relative to the body). Store the centroid in a variable, then call cpRecenterPoly() to make the poly's verts relative to that OR pass the negative centroid as the offset to the moment and shape init function.

Re: Strange bodies behaviour

Posted: Sat Dec 25, 2010 3:01 am
by shybovycha
Thanks! This one worked just perfect for me:

Code: Select all

cpVect center = cpCentroidForPoly(i + 1, verts);
cpRecenterPoly(i + 1, verts);
cpBody* mybody = cpSpaceAddBody(space, cpBodyNew(100.0f, cpMomentForPoly(1.0f, i + 1, verts, cpvzero)));
cpShape *myshape = cpSpaceAddShape(space, cpPolyShapeNew(mybody, i + 1, verts, cpvzero)); 
mybody->p = center;