O'Reilly logo

Cocos2d Cross-Platform Game Development Cookbook - Second Edition by Siddharth Shekar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding an accelerometer

In this section, we will discuss how to use the accelerometer in the device to move the object on screen.

Getting ready

Comment out or delete the touch function from the previous section to avoid any interference. In the header file, create a new sprite called accHero. Also, the motion is controlled by a motion manager, so create a new instance of this as well.

To add an accelerometer, we need to import the CoreMotion header as it is required to get the values for the accelerometer movements:

#import <CoreMotion/CoreMotion.h>
#import "SSCustomSprite.h"

@interface MainScene :CCNode{


  CCSprite* accHero;
  CMMotionManager *_motionManager;

How to do it…

In the MainScene.m file, we will modify the onEnter and onExit functions, as follows: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required