Book Image

Building Android Games with Cocos2d-x

By : Raydelto Hernandez
Book Image

Building Android Games with Cocos2d-x

By: Raydelto Hernandez

Overview of this book

Table of Contents (16 chapters)
Building Android Games with Cocos2d-x
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Handling the touch event


The most common way to create interaction between games and users is through touch events. Handling the touch event is very straightforward in Cocos2d-x.

In this section, we will allow the user to move our player sprite by touching it and moving it to the desired position.

The first thing that we will do is create the initTouch, movePlayerByTouch, and movePlayerIfPossible methods in the HelloWorldScene.h class header file, as we can see in the following code listing:

void initTouch();
void movePlayerByTouch(cocos2d::Touch* touch, cocos2d::Event* event);
void movePlayerIfPossible(float newX);

Now let us add the initialization code to the initTouch method in the implementation file HelloWorldScene.cpp. In this simple game, we are going to use a single touch that is going to be used to move around our bunny character, no multi-touch handling is required.

In order to handle the single touch, we will create a new instance of the EventListenerTouchOneByOne class, then we are...