Search code examples
iphonecocos2d-iphonechipmunkgravity

iphone cocos2d's chipmunk - Center of gravity


Here is my problem. I have a chipmunk's rigid body (a soda can standing up) that i want to change its center of gravity to the bottom of the object so it can fall on its flank when a force is applied to its upper part.

Am I on the right track?

1) For some reason, I am having trouble setting the body's center of gravity to a specific value. Anyone has an easy solution please?

2) What about the sprite's center of gravity? Do I need to change it as well? If so, how?

Thank you for clarifying that.

Yohann T.


Solution

  • Nevermind !

    I am answering my own questions since it was 16 hours ago and i got to find it on my own (yea it took me that long to figure it out, what a waste of time). Luckily for you, I am going to share the solution so you won't have to spend that many hours figuring out.

    1) For some reason, I am having trouble setting the body's center of gravity to a specific value. Anyone has an easy solution please?

    Answer: You can't change the center of gravity of a body because in a real simulated world, the center of gravity is NOT MODIFIABLE, unlesss you actually morph the object! ! !

    The way of doing it, is not to create a body with a "box" shape. You have to create the object using vertices so it can be affected by any type of physics, not just movement.

    here is the code I used to create a box around the object:

    int num = 4;
    cpVect verts[] = {
        cpv(-15,-15),
        cpv(-15, 15),
        cpv( 15, 15),
        cpv( 15,-15),
    };
    body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));
    body->p = cpv(-280, 240);
    cpSpaceAddBody(space, body);
    shape = cpPolyShapeNew(body, num, verts, cpvzero);
    shape->e = 0.0f; shape->u = 1.5f;
    shape->collision_type = 1;
    cpSpaceAddShape(space, shape);
    

    2) What about the sprite's center of gravity? Do I need to change it as well? If so, how?

    use this method:

    [sprite setTransformAnchor:ccp(27,54)];
    

    But remember that the coordinates starts at the bottom-left corner of the screen. But you won't have to touch the sprite if you handle the body's physics correctly.

    Good luck now !

    Yohann T.