28th December 2008

Gravity Tutorial for iPhone part 4

posted in Objective C, iPhone |

I have to admit, I'm writing these things for purely selfish reasons. Same reason I write books. You learn WAY more by teaching. If you think you are getting some knowledge from reading these, realize that I am getting SO much more knowledge and understanding from writing them. :)

Now let's use one of the really neat features of the iPhone, that lovely touch screen. There are three methods we can add to our view controller to listen for touch events: touchesBegan, touchesMoved, and touchesEnded. It inherits these from the UIResponder class, so you don't need to declare them, just implement them. Note that UIView is a UIResponder too, so you could put touches methods in there, but it makes more sense in this app to have it in the view controller, where we have a constant reference to the ball. To start with, add these method to GravityTutorialViewController.m:

C:
  1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  2.     NSLog(@"touches began");
  3. }
  4.  
  5. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  6.     NSLog(@"touches moved");
  7. }
  8.  
  9. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  10.     NSLog(@"touches ended");
  11. }

Open up your console and run the app and see that it does indeed respond to these actions.

You see that each method gets passed an NSSet of touches as a first parameter. An NSSet is "an unordered collection of distinct elements". Realize that the touch screen is multitouch, so a touch event may have several simultaneous touches going on - one for each finger. Here of course, we're really only concerned with a single touch. We get that by calling the anyObject method of the set. This will give us a single UITouch object. We can then call the locationInView method of the UITouch object to get a CGPoint showing the x, y location of that touch.

We'll store this point in a class variable, but let's actually make two, one for the last touch, and one for the current touch, so we can track movement and velocity. Declare these two in the view controller's .h file:

C:
  1. #import <UIKit/UIKit.h>
  2. #import "Ball.h"
  3.  
  4. @interface GravityTutorialViewController : UIViewController {
  5.     Ball *ball;
  6.     CGPoint lastTouch;
  7.     CGPoint currentTouch;
  8. }
  9.  
  10. - (void)onTimer;
  11.  
  12. @end

We don't need to make properties or synthesize these, as they are only used in the class. Now, we can grab the current touch location in each of the touch methods. Actually, we don't really need it in touchesEnded, as you'll see in a moment.

C:
  1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  2.     UITouch *touch = [touches anyObject];
  3.     currentTouch = [touch locationInView:self.view];
  4. }
  5.  
  6. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  7.     UITouch *touch = [touches anyObject];
  8.     currentTouch = [touch locationInView:self.view];
  9. }

First off, in touchesBegan, we need to see whether or not the user has touched the ball. Unlike in ActionScript where you have handy mouse down and mouse up and click events that tell you whether or not you clicked on something, here you have to do it all by hand. We'll just check the currentTouch location's distance from the ball's location. If that is less than the ball's radius, the user touched the ball.

Oddly enough, there doesn't even seem to be a built in distance method here, so we have to roll our own for that too. No problem though, we know Pythagorus quite well, right? A squared plus B squared and all that.

C:
  1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  2.     UITouch *touch = [touches anyObject];
  3.     currentTouch = [touch locationInView:self.view];
  4.     CGFloat dx = currentTouch.x - ball.position.x;
  5.     CGFloat dy = currentTouch.y - ball.position.y;
  6.     CGFloat dist = sqrt(dx * dx + dy * dy);
  7.     if(dist <ball.radius) {
  8.         ball.velocity = CGPointMake(0.0, 0.0);
  9.         ball.dragging = YES;
  10.     }
  11.     lastTouch = currentTouch;
  12. }

So, if the user has touched the ball, what do we do? First of all, we kill the velocity by setting it to 0.0. That way if he touches and releases it without moving, it will just drop to the floor, rather than continue on the way it was going.

Then we set the ball's dragging property to YES (true). I know, that property doesn't exist yet, but we'll be adding it soon. But first, let's wrap up the touch stuff. Finally, in this method, we assign the currentTouch to lastTouch so we know how far it moved, if and when it moves.

In touchesMoved, we need to move the ball to the current touch. Simple enough. We also need to update the velocity by subtracting the lastTouch from the currentTouch. In other words, how far did the touch move since last time? Well that's the ball's current velocity. If the user releases it, that's how fast it should go, and in what direction.

C:
  1. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  2.     UITouch *touch = [touches anyObject];
  3.     currentTouch = [touch locationInView:self.view];
  4.     ball.position = currentTouch;
  5.     ball.velocity = CGPointMake(currentTouch.x - lastTouch.x, currentTouch.y - lastTouch.y);
  6.     lastTouch = currentTouch;
  7. }

Finally, in touchesEnded, we just tell the ball we are not dragging it anymore.

C:
  1. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  2.     ball.dragging = NO;
  3. }

Now, onto this dragging stuff. We'll declare a BOOL variable in Ball.h and make it a property.

C:
  1. @interface Ball : NSObject {
  2.     CGPoint position;
  3.     CGPoint velocity;
  4.     CGFloat radius;
  5.     CGColorRef color;
  6.     CGFloat bounce;
  7.     CGFloat gravity;
  8.     BOOL dragging;
  9. }
  10.  
  11. @property CGPoint position;
  12. @property CGPoint velocity;
  13. @property CGFloat radius;
  14. @property CGColorRef color;
  15. @property CGFloat bounce;
  16. @property CGFloat gravity;
  17. @property BOOL dragging;
  18.  
  19. - (void)update;
  20. - (CGRect)getRect;
  21.  
  22. @end

And synthesize it in Ball.m:

C:
  1. #import "Ball.h"
  2.  
  3.  
  4. @implementation Ball
  5. @synthesize position;
  6. @synthesize velocity;
  7. @synthesize radius;
  8. @synthesize color;
  9. @synthesize bounce;
  10. @synthesize gravity;
  11. @synthesize dragging;
  12. ...

Finally, in the update method, we check to see if we are dragging the ball or not. If so, we just return. We don't want to do all that gravity and bouncing nonsense. We just want to let the user drag the ball.

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

That if statement up at the top is the only change to this method.

Now, we are about half way there. Oh, no, wait, we are done! Yup. Run the application (I still want to say "Test Movie" but I'm working on it) and you should have a dragable, throwable, bouncable, thoroughly lovable ball on your iPhone, iPod, or at very least, simulator.

Next up... accelerometer!

Post to Twitter

This entry was posted on Sunday, December 28th, 2008 at 1:43 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 13 responses to “Gravity Tutorial for iPhone part 4”

  1. 1 On December 28th, 2008, Willem said:

    Thanks for this. Very informative.

  2. 2 On December 30th, 2008, Bob said:

    I found a bug, or should i say something that might be improved in the code:

    the touchesMoved method should check for the ball.dragging or it will move the ball even though it hasn’t been pressed:

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    currentTouch = [touch locationInView:self.view];
    if( ball.dragging ) {
    ball.position = currentTouch;
    ball.velocity = CGPointMake(currentTouch.x – lastTouch.x , currentTouch.y – lastTouch.y );
    }
    lastTouch = currentTouch;
    }

  3. 3 On December 30th, 2008, Scott Janousek said:

    yay. Draggable gravity ball with touch access = success!

  4. 4 On December 30th, 2008, five March said:

    Nice tutorial, great to start, then i wanted to have two balls… but BallView, being like a DisplayObject in CS3 supports only one drawRect(?),
    (like you said, indeed, doing it yourself means learning)
    so creating in GravityTutorialViewController.h :

    IBOutlet UIImageView *moon;
    IBOutlet UIImageView *sun;

    and connecting the Outlets in the interface builder to the File’s Owner
    and doing
    - (void)onTimer {

    [ball update];
    moon.center = ball.position; //the images use the ball positions
    [ball2 update];
    sun.center = ball2.position;

    [(BallView *)self.view refresh:ball];

    }
    in GravityTutorialViewController.m
    (having init’s for both balls, with different parameters)
    so this gave two nice jumping balls
    (the balls being images imported in the Image View objects in the interface.)

    i like the images more then the circles,
    trying to do the same trick with UIView objects in the interface builder didn’t work like the UIImageView objects, i’ll have to look into that more in detail

    probably the UIView BallView is still drawing the circles underneath the images…
    :-) …..i’ll have to organize this

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

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

  6. 6 On January 13th, 2009, Matthi’s kleine Welt » iPhone SDK & OpenGL ES - Erste Versuche said:

    [...] Tutorial Part 1, Part 2, Part 3, Part 4, Part [...]

  7. 7 On January 13th, 2009, snowytree said:

    Great tutorial, great site! Thanks for the clear and simple instructions.

  8. 8 On February 4th, 2009, George said:

    I’m Sooooo glad someone could put this in terms of actionscript, even for people without actionscript knowlage i’d have to say it’s one of the best tutorials out there. Thanks a million =].

    Very small improvement, if you don’t do what bob said and you’d prefer to have the throw action occur everytime you touch the screen no matter where (like in the code) then add ball.dragging = YES; inside the touchesMoved event, this means that if you throw the ball starting a a location outside the radius of the ball, it won’t drop if you keep the touch still

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

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

  10. 10 On March 9th, 2009, Krish said:

    how to use a pagecontrol and drag this ball from the first page to the second page

  11. 11 On June 21st, 2009, Geoff said:

    Keith!

    These tutorials are great. You should include a link to the next one at the bottom of each one, though, so it’s easier to go through them in order!

  12. 12 On January 11th, 2010, Alex said:

    Good tutorial, doesn’t actually work due to the “-[UIView refresh:]: unrecognized selector sent to instance” problem but non the less very informative. I’ve absorbed loads just from following the code :) I have a feeling though that with just a very basic understanding of view and object typing I could have fixed the error I mentioned above (and a few others did before me). So that’s next for me.

  13. 13 On January 11th, 2010, Alex said:

    Sorry, everything’s working perfectly fine. As the idiot I am I skipped certain parts of the text which explained perfectly well that we needed to change the view used by the controller to our new BallView. As I hadn’t done that, the type of view I was trying to refresh differed from the default one! So in a nutshell I was trying to send a UIView to a method that takes a BallView, pffft.

    Great tutorial, and sorry again for bashing your fully functional code :)

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