30th December 2008

Gravity Tutorial for iPhone, Part 5

posted in Objective C, iPhone |

For the final installment in this series, we'll add accelerometer support to the ball, allowing you to tilt the device to change the direction of "down". Note, although you can rotate the device in the iPhone simulator, this does not simulate acceleration. The only way you'll be able to see this in action is on a physical device. This means that you'll have to pay $99 sign up for and be accepted to the iPhone Developer program, and figure out how to provision apps to your device. I'm not going to cover that here, so I'll assume that you've figured that out on your own. OK, let's jump in.

So far, we have gravity in the ball, affecting its y velocity. If we know which way the device is tilted, we can change that to affect the velocity on the x axis as well, proportional to the degree of tilt. For example, if you tilted the device 90 degrees to the left, gravity should only affect the x velocity. If you turn it upside down, it will affect only the y velocity again, but in the opposite direction. In most cases, it will not be exactly straight, so there will be some x velocity and some y, proportional to the angle of tilt.

To respond to acceleration, we need to do three things:

1. Have a class specify the UIAccelerometerDelegate protocol. This is similar to implementing an interface in ActionScript. But less strict. It's telling the application that you expect this class to respond to acceleration, and it may have some of the methods associated with this protocol. But unlike an interface, you are not required to implement all or even any of the methods.

2. Set the class as a delegate for accelerometer events. Think of this as adding an event listener.

3. Create a method to respond to the events. Here is where you will change gravity.

OK, step 1, specifying the protocol. We'll have the Ball class do this directly, as that's where gravity is. You just put the protocol name in angle brackets after the class name and and super classes, like so:

C:
  1. @interface Ball : NSObject <UIAccelerometerDelegate> {
  2. ...

I'm not really sure what this does to be honest, as it seems you can be a delegate without specifying the protocol (although you will get a warning), and you can specify the protocol without being a delegate. But you're supposed to do it, so do it. :)

Step 2. Set self as a delegate. We'll do that in the init method in Ball.m:

C:
  1. - (id) init
  2. {
  3.     self = [super init];
  4.     if (self != nil) {
  5.         position = CGPointMake(100.0, 100.0);
  6.         velocity = CGPointMake(5.0, 5.0);
  7.         radius = 20.0;
  8.         color = [UIColor greenColor].CGColor;
  9.         bounce = -0.9f;
  10.         gravity = 0.5f;
  11.         dragging = NO;
  12.         [[UIAccelerometer sharedAccelerometer] setDelegate:self];
  13.     }
  14.     return self;
  15. }

sharedAccelerometer is a class (static) property of the UIAccelerometer class, I assume it's like getInstance of a Singleton. You are calling setDelegate on that object, passing self (this). Simple enough.

Step 3. Create a method which will be called on acceleration. Again, right in Ball.m:

C:
  1. - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
  2.     NSLog(@"x: %f, y: %f", acceleration.x, acceleration.y);
  3. }

You don't need to declare this, as you specified the protocol, which, come to think of it, is probably why you set the protocol.

The method is called accelerometer and passes a pointer to a UIAccelerometer object, and a pointer to a UIAcceleration object. It's this last one we're interested in, as that will tell us the amount of tilt.

Here I've just put in a log statement so you can see that it's working. The acceleration parameter passed in will contain x, y, and z properties, which will range from -1.0 to +1.0. We're only interested in x and y. x will be -1.0 when the device is tilted 90 degrees to the left, 0.0 when it's upright and +1.0 when tilted to the right. Likewise, y will be -1.0 when upright, and vary towards 0.0 on either side, and then to +1.0 when the device is upside down.

So, rather than a single value for gravity, we'll need x and y values for gravity. We can store these in a point object. Declare it in Ball.h:

C:
  1. CGPoint acceleratedGravity;

Leave gravity there, as that will affect the overall strength of gravity and generally stays the same. This new variable will change constantly according to tilt.

You can also initialize this in the init method:

C:
  1. acceleratedGravity = CGPointMake(0.0, gravity);

Note that the x value is initialized to 0.0 and y to gravity, indicating no rotation.

Now we can change the acceleration method to alter this variable:

C:
  1. - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
  2.     acceleratedGravity.x = acceleration.x * gravity;
  3.     acceleratedGravity.y = -acceleration.y * gravity;
  4. }

Note that the y value is reversed, otherwise the ball would fall "up".

Finally, we just need to alter the update method in Ball.m to utilize acceleratedGravity instead of just gravity:

C:
  1. - (void)update {
  2.    
  3.     if(dragging) return;
  4.    
  5.     velocity.x += acceleratedGravity.x;
  6.     velocity.y += acceleratedGravity.y;
  7.     position.x += velocity.x;
  8.     position.y += velocity.y;
  9. ...

And that's it! Pretty simple actually. Now you tilt the device and the ball will always fall "down". It will settle in a corner, or on the "top" of the device, or whatever direction is down. Amazing just how easy that was. Less than 10 lines of code in all.

And that brings us to the end of this series. Bear in mind that I'm a beginner at this stuff, and was writing this for my own selfish reasons - to learn the language and drill it into my head. I've already seen several places where the code in this project is not up to snuff at all. I may go back and correct it at some point, but I'll just say for now to take what I've written here as a jump start. It will get you up and running, but you really need to learn more about the right way to do things, like I am already doing. And if you find something that indicates I did something incorrectly, it's probably right.

Post to Twitter

This entry was posted on Tuesday, December 30th, 2008 at 11:02 am and is filed under Objective C, iPhone. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 22 responses to “Gravity Tutorial for iPhone, Part 5”

  1. 1 On December 30th, 2008, baDa said:

    Dude, i really wanna thank you!

    all posts of this tutorial, are simple and clear for me, who never develop in iPhone SDK!

    Plz keep this good posts!

    And u recommend the book of first tutorial, for who never develop in sdk before? Or another?

  2. 2 On December 31st, 2008, IPhone SDK - tutoriaux par Keith Peters | tweenpix said:

    [...] Voici la liste complète des tutoriaux: – Part 1 – Part 2 – Part 3 – Part 4 – Part 5 [...]

  3. 3 On January 3rd, 2009, sascha/hdrs said:

    Great tutorial really!!

    But this just spoiled my day: “This means that you’ll have to pay $99 sign up for and be accepted to the iPhone Developer program”!

  4. 4 On January 4th, 2009, Anthony said:

    Great tutorial!

    First one that I’ve read that does something interesting while still explaining every bit of code. Could you post those references that show that your code is “not up to snuff.” ?

  5. 5 On January 7th, 2009, jake said:

    any chance of getting the source code. .i tried following and i must of missed something and i cant seem to find where the error is.

  6. 6 On January 8th, 2009, KANG said:

    Amazing! Wrote an iPhone app, that I understand, with graphics, accelerometer, touch sensitivity, all within 45 minutes! Your tutorial is great!

    Only catch is that the simulator does not seems to have accelerometer built in, strange, so I can’t test if the tilt really works. Must download it into a friend’s iPhone next to try this.

    Thank you man!

  7. 7 On January 13th, 2009, Pasi Manninen said:

    Great Tutorial!

    Example runs nicely in iPhone too!

  8. 8 On January 14th, 2009, Al said:

    Thanks very much for taking the time to write these tutorials.

    Explaining things in actionscript terms has really helped me get up to speed. Although there are still quite a few syntactical oddities in Objective-C that leave me slightly confused.

    Fun fun

    Cheers

  9. 9 On January 22nd, 2009, Thierryb said:

    Is possible to download the tutorial ?

    Thanks a lot for your work.

    Thierry

  10. 10 On January 31st, 2009, Andy said:

    Thanks,
    I am a Visual Studio guy and have been for years. Your tutorials have been very helpful in crossing the gap.

  11. 11 On February 24th, 2009, イナヅマtvログ » iPhone SDK + Objective-C, 参考サイト メモ said:

    [...] Gravity Tutorial for iPhone – Part 5 [...]

  12. 12 On April 6th, 2009, John said:

    I tried to follow along and made a few mistakes. Where can I find the source code?

  13. 13 On April 8th, 2009, Smita said:

    It is a wonderful tutorial. I tried following the steps. However getting some errors. Do you have tutorial source code? Thanks in advance.

  14. 14 On June 2nd, 2009, Shoaibi said:

    Can you please add the complete sample code so i can actually see a demo of what would be the end product?

  15. 15 On July 2nd, 2009, armen said:

    Thx for great tutorial.
    Im having some errors when trying to compile…. can’t find a way to fix them.
    Can u please post complete code of the working project, so i can compare with mine and see whats wrong?
    thx!

  16. 16 On July 13th, 2009, Jack Cardinal said:

    Awesome tutorial! Thanks for relating this all to ActionScript.

  17. 17 On September 10th, 2009, Ian said:

    Well, we all know you can’t do pinball in Flash.

  18. 18 On September 10th, 2009, kp said:

    Ian, yes, this has been proven. :)

  19. 19 On October 25th, 2009, iPhone gravity tutorial – code « rawjam.co.uk – blog said:

    [...] Yesterday I started looking around Google to see if I could find a suitable tutorial that would help me understand how to impliment ‘gravity’ like functionality. In essence, I needed to be able to flick an object on the screen, have it bounce around a little and then fall back to earth. I found a great tutorial that (through 5 seperate blog posts) leads you through each of the required stages. I HIGHLY recommend that you check it out (http://www.bit-101.com/blog/?p=1824). [...]

  20. 20 On October 25th, 2009, Ben said:

    Great set of tutorials. I have created a more generic version of this code so that it can easily be re-used. I am also providing all source code. Feel free to check it out at http://blog.rawjam.co.uk/index.php/development/iphone-gravity-tutorial-code/

  21. 21 On November 16th, 2009, chaoz said:

    Great Tutorial! But I wanted to know, if it’s possible to add more than just one ball and use them all like you do in this tutorial? I was experimenting a little bit, but I didn’t get any positive result :( . I tried to use the Ball-Class as an array of objects. Does somebody have any ideas? Please let me know.

  22. 22 On December 22nd, 2009, Mohammed Iliyas said:

    Great Tutorial. I was learning iphone app development for past 2 months. Because my root knowledge of programming is from Action Script, even after learning the basics of development i always got some confusion. This tutorial gave more clear idea about how to transfer the flash knowledge to iphone. It will be great if you write a book on actionscript to iphone. Thanks

Leave a Reply

Who is reading BIT-101?

Copyright ©2009 by Keith Peters. All rights reserved. This means that you may not reprint or repost the contents of this site without express written permission of the author.


  • Calendar

  • February 2010
    M T W T F S S
    « Jan    
    1234567
    891011121314
    15161718192021
    22232425262728
hoodia order buy Levitra Plus betablockers weight loss information buy pills without a prescription arthritis menopause ambien doses cat's eye health information on cholesterol cialis online order valtrex cheapest phentermine onlin e increase breast size lower blood sugar immediately terramycin which is better cialis or viagra buy cheap cialis reduce cholesterol naturally new blood pressure treatment products for back pain cheapest cialis index will levitra help piroxicam 20 mg order viagra online in germany buy tadalafil online buy levitra onlines how to naturally lower cholesterol buy generic viagra where to buy soma anti allergic drug levothyroxine dogs new hair loss treatmen buy levitra pain meds buy cheap malaria therapy weight loss after baby asthma medications chronic snoring viagra gel prostate cancer cures order viagra cialis alprazolam men health natural cure arthritis immune system support diet medicine cialis approval lipitor effects where can i buy arthritis drugs overactive bladder in men self help weight loss natural cholesterol control ativan medication cialis approval best cure for snoring breast enhancing pills order prozac celebrex pharmacy buy levitra onlines premature ejaculation cure confidence hypnotherapy free stop smoking bust enhance diet weight loss supplements skin fungal infection valium with no prescription viagra with out prescription breast enhancement products alpha blocker medications azithromycin 250mg skin disease chronic heart failure medicines dog care products buying cialis online gerd in children antibiotics to buy my drug store muscle building diet drugs affecting levitra anti anxiety medications really large breast enhancement help for constipation ulcers stomach drugs for high blood pressure selling pet products buy pain medicine viagra online overnight fucidin ointment generic zyrtec prices soft tab cialis smoking treatment dog products online weight loss solution cialis on line blue pills weight loss diet pill nitroglycerin sublingual floxin prevention of heart attack imuran order gasex vermox treatment of depression Viagra On Line buy generic cialis professional tooth whitening kits to buy valium 2mg treatment for hypertension ultram cheapest online stores hair loss products cheap weight loss diovan prescription malaria preventative taurine treating prostate cancer immune system support natural constipation cure phentermine no prescription fast delivery purchase meds without prescription buy plendil diet drug taking viagra after cialis protonix cheapest generic cialis online viagra levitra cialis yohimbe benefits muscle mass gain diet and health products medical treatment for insomnia buy blood pressure meds buy celexa levaquin interactions blood pressure drug skin disorder where can i buy arthritis drugs natural breast enhancer acute pain control online diazepam natural acne remedy antifungal strategies triphala pravachol online how can i stop smoking breast enhancement natural nautral breast enhancement beta blocker medications wellbutrin dosages order viagra cialis lower high blood pressure mass muscle phentermine from canada how to loss weight osteoporosis bone health lipitor use dog medication drug allergies buy diazepam buyviagra cialis phentermine 37.5 mg zestril medication parkinsons treatment generic revatio free nexium cosmetic dentistry tooth whitening avalide generic buy cheap tadalafil uk simvastatin tablets buy cialis online in usa breast pain cat care ovulating clomid medical skin care lines viagra to canada viagra or cialis cheap cialis tramadole buy azulfidine drugs used for cancer ear pain oral ketoconazole raloxifene evista taurine sex with levitra stop smoking today heart failure natural cholesterol control protonix dose oxybutynin 5mg irritable bowel syndrome treatments new treatment for hepatitis c cheap prescription drugs viagra online prescription depression therapy buy sumycin menopause treatment hair loss treatments medication pletal what is a natural antibiotic viagra purchase synthroid tablets generic prilosec lipitor cat health info discount vitamin cholesterol and health bacterial diarrhea weight loss medicine new treatment for depression removing retention fluids diuretic medicines soma 250mg cat anxiety loss weight online pharmacy viagra buy phentermine without a prescription herbs for breast growth cymbalta dosage fast weight loss supplement arthritis menopause levitra online order cheapest place to buy phentermine cold flu medications for nausea buy ultram where pills for acne free weight loss programs help with anxiety improve skin valium 2mg urinary tract health cat urinary tract disease crestor dosage drug zofran calan zyrtec buy nirdosh dosage digoxin buy pain patch acomplia alendronate cialis best price cheap wellbutrin small dog products depression medicine sildenafil dosage dog health depression and anxiety lamictal withdrawal viagra, levitra and cialis online drug buy bone maker strontium cures for hair loss nitroglycerin tablets natural arthritis treatment arimidex buy buy energy patch how to treat a yeast infection viagra herb alternative viagra cialis levitra order sublingual cialis cialis comparison breast lift augmentation seroquel for depression carisoprodol mg new treatment for depression cialis soft tabs safe sleep aid severe leg muscle pain natural weight loss gabapentin medication what is ambien clozapine medication viagra online ordering cures for hair loss free weight loss help buy viagra levitra pet treats order plan b diabetes type 2 phentermine risk ultram er side effects treatment for hepatitis b constipation cures drugs used in treating depression leg pain buy cheap generic cialis anti anxiety meds hypnotherapy for weight loss motilium body building fitness dog skin relieve upper back pain cures for high blood pressure cardura celecoxib Viagra Online Cheap cheap bactrim ambien online lamisil cost infertility meds progesterone clomid osteoporosis hormon urinary tract infection symptoms hypnotherapy for health how to buy viagra online joint pain cure online allegra buy generic cialis uk generic abilify cures for lung cancer new treatments for lung diseases pain meds buy cheap treatment for dry skin disease of the skin nexium drug free stop smoking buy tooth whitening products viagra tablet naprosyn dosage women's fertility male sexual power carisoprodol purchase asthma attack treatment estradiol pills phentermine from canada pet health care hair loss products online astelin generic cheap estrace free weight loss program buy rimonabant relieve lower back pain lexapro prescription new breast cancer drug buying ambien best online viagra scams home scabies treatment hair loss in woman buy generic cialis uk eye drop gabapentin medication amitriptyline uses ultram no prescription natural pain cures buy cla products back pain lowest price generic viagra pain meds buy cheap mg buy phentermine acne skin care cialis rx weight loss and fitness nitrofurantoin buy phentermine without a prescription high blood pressure medicines stop hair loss viagra china use levitra female health coreg dosage carisoprodol price pain relief product breast enlargement depression pills buy how to treat flu home neck pain relief order imitrex online vitamin b-6 cialis soft tabs pharmacy software description of soma buy isoniazid cheap prevacid help ear infections on dog fat burning stop smoking remedies rhinitis treatment chronic pain relief birth control online meds without prescriptions buy lovastatin drug stores penis enlargement without pill cancer medicine buy deltasone cure for throat infection thyroid dogs dosage cipro viagra from uk cheap alcoholism treatment natural cure for constipation paxil cialis 5mg tablets amitriptyline uses topamax drugs lower heart rate drug discount codes dog medicines body fat loss joint pain recurring urinary tract infections ativan information buy drugs online cheap fast valium body building ambien maximum dosage information on valium how to sperm more chlamydia medication dosage buy cialis online viagra chest pain heart fluconazole interaction calcium channel blocker side effects zolpidem dosage online drug stores zelnorm muscle strength fluconazole buy stress gum free weight loss products information on gout low immune system online viagra cialis 20 buy cefixime phentermine from canada gain muscle mass fast lasix side effects buy singulair penis enlargement free natural muscle and joint health viagra online overnight cialis online aceon allergies and asthma diamox side effects weight loss software generic compazine price for tramadol high blood pressure symtoms osteoporosis help treatment severe constipation drug new smoking stop pain relief product xanax online dog health info clonazepam .5mg buy tribulus pregnancy prevention methods allergy hives