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 – handling multitouches


There are three methods we need to implement in this game to handle touches. Each method receives, as one of its parameters, a vector of Touch objects:

  1. So add our onTouchesBegan method:

    void GameLayer::onTouchesBegan(const std::vector<Touch*> &touches, Event* event)
    {
       for( auto touch : touches) {
         if(touch != nullptr) {
            auto tap = touch->getLocation();
            for (auto player : _players) {
             if (player->boundingBox().containsPoint(tap)) {
                player->setTouch(touch);
             }
           }
         }
       }
    }

    Each GameSprite, if you recall, has a _touch property.

    So we iterate through the touches, grab their location on screen, loop through the players in the vector, and determine if the touch lands on one of the players. If so, we store the touch inside the player's _touch property (from the GameSprite class).

    A similar process is repeated for onTouchesMoved and onTouchesEnded, so you can copy and paste the code...