Book Image

Cocos2d-x by Example: Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-x by Example: Beginner's Guide

By: Roger Engelbert

Overview of this book

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – adding our main loop


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

  1. We will update the puck's velocity with a little friction applied to its vector (0.98f). We will store what its next position will be at the end of the iteration, if no collision occurred:

    void GameLayer::update (float dt) {
       
        auto ballNextPosition = _ball->getNextPosition();
        auto ballVector = _ball->getVector();
        ballVector *=  0.98f;
        
        ballNextPosition.x += ballVector.x;
        ballNextPosition.y += ballVector.y;
  2. Next comes the collision. We will check collisions with each player sprite and the ball:

    float squared_radii = pow(_player1->radius() +  _ball->radius(), 2);
    for (auto player : _players) {
      auto playerNextPosition = player->getNextPosition();
      auto playerVector = player->getVector();  
      float diffx = ballNextPosition.x - player->getPositionX();
      float diffy = ballNextPosition.y - player->getPositionY();
      float distance1 = pow(diffx, 2) + pow(diffy,...