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:

- (void)onEnter
{
    [superonEnter];
self.userInteractionEnabled = YES;
[_motionManagerstartAccelerometerUpdates];
}

- (void)onExit
{
    [superonExit];
self.userInteractionEnabled = NO;
[_motionManagerstopAccelerometerUpdates];
}

As for the touches, we will enable and disable them in the onEnter and onExit functions. Similarly, the accelerometer updates have to be enabled and disabled accordingly in each class you use it in.

In the init function, we will initialize the sprite and motion manager via the following code:

//accelerometer
accHero = [SSCustomSpritespriteWithImageNamed:@"hero.png"];
accHero.position = ccp(self.contentSize.width/2, self.contentSize.height/2);
[selfaddChild:accHero];

_motionManager = [[CMMotionManageralloc] init];

Next, we have to update the position of the hero sprite in the update function, as follows:

// update function
- (void)update:(CCTime)delta {
  CMAccelerometerData *accelerometerData = 
    _motionManager.accelerometerData;

  CMAcceleration acceleration = accelerometerData.acceleration;
  CGFloatnewXPosition = 
    accHero.position.x + acceleration.y * 1000 * delta;

  newXPosition = clampf(newXPosition, 0, self.contentSize.width);

  accHero.position = 
    CGPointMake(newXPosition, accHero.position.y);
}

How it works…

Now, run the application and watch the character move back and forth by tilting the device.

Unlike touches, which have their own functions that get triggered whenever a touch starts, changes location, or gets removed, an accelerometer doesn't have a function of its own. However, the motion manager has the accelerometer data for each update, so we will always use the update function to get and set the values retrieved from it.

Unfortunately, you need a device to check whether it works as the simulator won't be able to simulate it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.79.147