Search code examples
iphonecocos2d-iphonebox2dgame-physics

Forever moving ball


How do I create a body [A ball Body] that will bounce around the screen, never losing or gaining speed, regardless of what it hits in cocos2d-box2d?


Solution

  • Set restitution of the fixture to 1, and friction to 0.

    Box2D manual says:

    Restitution is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. <...> A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision.

    A friction value of 0 turns off friction

    Without friction and with perfectly elastic collision your ball will bounce around the screen, never losing or gaining speed in a static environment. If environment is not static, then colliding with moving object will change speed of the ball.

    To solve this problem, I suggest next trick. Set contact listener, and in PostSolve method correct speed of you ball like this:

    void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
    {  
       if(contact->GetFixtureA()->GetBody() == YOUR_BALL_BODY ||
          contact->GetFixtureB()->GetBody() == YOUR_BALL_BODY)
       {
           float speed = YOUR_BALL_BODY->GetLinearVelocity().Length();
           float koef = YOUR_NEEDED_SPEED / speed;
           YOUR_BALL_BODY->SetLinearVelocity(koef * YOUR_BALL_BODY->GetLinearVelocity());
       }
    }
    

    How to set contact listener see there.