In this section, we will discuss how to use the accelerometer in the device to move the object on screen.
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;
In the MainScene.m
file, we will modify the onEnter
and onExit
functions, as follows:
- (void)onEnter { [superonEnter]; self.userInteractionEnabled = YES; [_motionManagerstartAccelerometerUpdates]; } - (void)onExit { [superonExit]; self.userInteractionEnabled = NO; [_motionManagerstopAccelerometerUpdates];...