A small game about ball collision in IOS

Source: Internet
Author: User

This game is about a ball moving randomly on the screen. You can use your fingers to manipulate a ball. If the two balls collide with each other, it means losing. A very simple game.



Define two UIImageView and one start button in StoryBoard



Link the two uiimageviews to the code.

@ Property (weak, nonatomic) IBOutlet UIImageView * player;

@ Property (weak, nonatomic) IBOutlet UIImageView * enemy;

@ Property (weak, nonatomic) IBOutlet UIButton * start;


Define the ball moving rate in ViewDidLoad

Pos = CGPointMake (5.0, 4.0 );

If you click start

-(IBAction) start :( id) sender {[self. start setHidden: YES]; // start a timer and let the player ball randomly move randomMain = [nst1_scheduledtimerwithtimeinterval: 0.03 target: self selector: @ selector (onTimer) userInfo: nil repeats: YES];}-(void) onTimer {[self checkCollision]; self. enemy. center = CGPointMake (self. enemy. center. x + pos. x, self. enemy. center. y + pos. y); if (self. enemy. center. *> 320 | self. enemy. center. x <0) {pos. x =-pos. x;} if (self. enemy. center. y> 480 | self. enemy. center. y <0) {pos. y =-pos. y ;}}- (void) checkCollision {// checks whether the two balls have collided with each other if (CGRectIntersectsRect (self. player. frame, self. enemy. frame) {[randomMain invalidate]; [self. start setHidden: NO]; CGRect frame = [self. player frame]; frame. origin. x = 137.0f; frame. origin. y = 326366f; [self. player setFrame: frame]; CGRect frame2 = [self. enemy frame]; frame2.origin. x = 137.0f; frame2.origin. y = 20366f; [self. enemy setFrame: frame2]; UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "ball is catched" message: @ "you have to play again" delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: nil]; [alert show] ;}}
The code can be downloaded

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.