Time for action – adding our main loop

This is the heart of our game - the update method:

  1. We update the puck's velocity, with a little friction applied to its vector (0.98f). We store what its next position will be at the end of the iteration, if no collision occurred:
    void GameLayer::update (float dt) {
        CCPoint ballNextPosition = _ball->getNextPosition();
        CCPoint ballVector = _ball->getVector();
        ballVector = ccpMult(ballVector, 0.98f);
        ballNextPosition.x += ballVector.x;
        ballNextPosition.y += ballVector.y;
  2. Next comes collision. We check collision between each player sprite and the ball:
    GameSprite * player; CCPoint playerNextPosition; CCPoint playerVector; float squared_radii = pow(_player1->radius() + _ball->radius(), 2); for (int p = 0; p < _players->count(); ...

Get Cocos2d-x by Example Beginner's Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.