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 touches


We need to implement onTouchBegan, onTouchMoved, and onTouchEnded.

  1. Now in GameLayer.cpp, inside onTouchBegan, add the following lines:

    if (!_running) return true;
    Point tap = touch->getLocation();
    float dx = _rocket->getPositionX() - tap.x;
    float dy = _rocket->getPositionY() - tap.y;
    if (dx * dx + dy * dy <= pow(_rocket->getRadius(), 2) ) {
     _lineContainer->setLineType ( LINE_NONE );
     _rocket->setRotationOrientation ( ROTATE_NONE );
     _drawing = true;
    }
    
    return true;

    When a touch begins, we only need to determine whether it's touching the ship. If it is, we set our _drawing property to true. This will indicate we have a valid point (one that began by touching the _rocket sprite).

  2. We clear any lines we may be currently drawing in _lineContainer by calling setLineType( LINE_NONE ), and we make sure _rocket will not rotate until we have a pivot point by releasing _rocket (setRotationOrientation ( ROTATE_NONE )), so it will continue to move...