Accelerometer and Sprite Kit

Hi again everyone. Since Apple released iOS 7 I figured it was time to do another quick tutorial on the Accelerometer and Sprite Kit. Sprite Kit is VERY similar to Cocos2d for iPhone. I was able to take my last tutorial, Accelerometer and Cocos2d, and port it over pretty quickly.

First start with a new project and select “SpriteKit Game” as the template. You now have a working project that will show display “Hello World” on a black background. Open the ViewController.m file and change the skView.showsFPS and skView.showsNodeCount to NO.

Then, Go to the MyScene.m file. Delete everything inside of the brackets after the first if statement in the initWithSize method so it looks like this:

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {

}
return self;
}

Next, delete the entire touchesBegan method since we won’t need it at all in this tutorial. Now we have a blank project to work with.

Open MyScene.h and add a SKSpriteNode: SKSpriteNode *monkey;. Then open MyScene.m and this to the initWithSize method from above to add the monkey (or any sprite) to the scene:
monkey = [SKSpriteNode spriteNodeWithImageNamed:@"monkey_arms_up.png"];
monkey.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
[self addChild:monkey];

Add this line to make the background white so it’s easier to see:
self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

If you build and run now, you should have the monkey in the middle of the screen with a white background. To move the monkey left and right its pretty simple, in fact, it’s almost exactly how it was in cocos2d! First add the CoreMotion framework to your app and #import in your MyScene.h file. Also add CMMotionManager *motionManager; to your .h file. Back in the .m file, add this #define kPlayerSpeed 250 at the top under the implementation line. Then add this in the initWithSize method under where we set up the monkey before.


motionManager = [[CMMotionManager alloc] init];
if ([motionManager isAccelerometerAvailable] == YES) {
[motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
withHandler:^(CMAccelerometerData *data, NSError *error)
{
float destX, destY;
float currentX = monkey.position.x;
float currentY = monkey.position.y;
BOOL shouldMove = NO;

if(data.acceleration.y < -0.25) { // tilting the device to the right destX = currentX + (data.acceleration.y * kPlayerSpeed); destY = currentY; shouldMove = YES; } else if (data.acceleration.y > 0.25) { // tilting the device to the left
destX = currentX + (data.acceleration.y * kPlayerSpeed);
destY = currentY;
shouldMove = YES;
}
if(shouldMove) {
SKAction *action = [SKAction moveTo:CGPointMake(destX, destY) duration:1];
[monkey runAction:action];
}
}];
}

Hope this was easy to follow, let me know if there are any errors in the code on twitter @jon01. All of the code can be downloaded from my github.