Welcome to my Programming Blog...

I am currently working on a couple of projects: An original game called "Implosion" which I am porting from Flash to the iPad, and a remake of Q*bert in Python (pygame), as part of the class I am teaching. Please feel free to use the "Labels" (at right) to follow a specific project or theme. If you are one of my Python students, I recommend that you check out the Python thread.

Thursday, January 13, 2011

Accelerate this!

Getting the accelerometer to work on your iOs device is actually not very hard - you just need to activate it in your program, and implement one function. To activate it, you go to the init function of your main scene and say:
self.isAccelerometerEnabled = YES;
This will cause the built-in accelerometer in the iPhone, iPod or iPad call the Accelerometer: didAccelerate: function over and over. You have to make sure you write this function! Here's an example that updates a CCLabelTTF object called "status" with the x,y, and z accelerations:
-(void)accelerometer: (UIAccelerometer*) accelerometer        
       didAccelerate:(UIAcceleration*)acceleration
{
    [status setString: [NSString stringWithFormat:@"X:%3.2f, Y:%3.2f, Z:%3.2f",
                acceleration.x, acceleration.y, acceleration.z]];
}
(The "%3.2f"s in the string will get replaced by the numbers that follow the string, formatted as numbers that go to the 1/100ths place.)
If you try running this in the simulator, you will get nothing happening - there is no accelerometer. However, if you run this on an actual device, you will see three numbers, each of one will mostly vary from -1 to +1. If you hold the device so that the square menu button is at the bottom, then "y" represents the up/down direction, "x" represents left/right and "z" represents towards/away from you.
A piece of advice: don't make the accelerometer code take very long - keep it short. You might use it to change your player's velocity, or maybe to change it's position, but don't go searching through the list of all your enemies to detect collisions - that's what update: is for. You want the response from the accelerometer to be fairly crisp.
Here is an example project, which includes the ability to change how often the accelerometer is "triggered" - there is, of course, an upper limit on how often it can fire, but some applications may only need to check on the orientation of the device every few seconds...

No comments:

Post a Comment