Physical knowledge application in iOS animations-collision detection

Source: Internet
Author: User

Collision detection

I believe that the people who engage in iOS, more or less know pinball this little game. By hitting different points, you can change the trajectory of the motion. For many people, if you do not know the idea may feel the ball in the screen hit, hit the wall to change the direction of movement seems difficult to achieve.
In fact, this only requires a little bit of basic iOS graphics and Animation Foundation, but also a little bit of physical knowledge is OK.

1. Speed and displacement are vectors

In a 2D coordinate system, velocity and displacement can be decomposed into components on the X and Y axes.

So the motion of the object can be described in terms of speed in VX and VY. Each time the interface refreshes, the object's speed component, VX and VY, is used to calculate the position of the next object:

    • Next x axis coordinate =VX + current x coordinate
    • Next y-axis coordinate =vy + current y-coordinate
2. Velocity model of collision


Suppose the object hits the bottom edge of the screen, when the object is in the direction of the x-axis, the speed in the y-axis is reversed, and it hits the top edge of the screen.
Physical Model:

    • VX = VX
    • Vy =-Vy

Similarly, if the object hits the left or the right:

    • VX =-VX
    • Vy = Vy
3. Code implementation 1. Create a new Mrview to add to the root view.

2. Add Cadisplaylink

Cadisplaylink is a timer that allows us to draw content to the screen at the same frequency as the screen refresh rate. We create a new Cadisplaylink object in the app, add it to a runloop, and give it a target and selector call when the screen refreshes.

*link = [CADisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)];[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
3. Set member properties
//Birds pictures@property(nonatomic,Strong)UIImage*imagebird;//Bird's location@property(nonatomic,Assign)CGFloatBIRDX;@property(nonatomic,Assign)CGFloatBirdY;//Bird's speed@property(nonatomic,Assign)CGFloatBirdspeedx;@property(nonatomic,Assign)CGFloatBirdspeedy;
4. Initialization

It is important to note that in order to set up from Xib,storyboard, there must be references to the initialization of the code. Cadisplaylink called Setneedsdisplay is used to redraw continuously.

//Initialize call from Xib or storyboard- (void) awakefromnib{[ SelfSetupbird];}//Call this from code initialization-(Instancetype) initWithFrame: (CGRect) frame{if( Self= [SuperInitwithframe:frame]) {[ SelfSetupbird]; }return  Self;} -(void) setupbird{ Self. BackgroundColor= [UicolorBlackcolor]; Cadisplaylink *link = [Cadisplaylink displaylinkwithtarget: SelfSelector@selector(Setneedsdisplay)]; [link Addtorunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; Self. Imagebird= [UIImageimagenamed:@"Qq20150714-1"];//Set initial position     Self. BIRDX=1; Self. BirdY=1;//Set initial speed     Self. Birdspeedx=5; Self. Birdspeedy=5;}
5. Drawing

The main is to judge good, the birds collide around when the speed of the reverse

- (void) DrawRect: (CGRect) rect{[ Self. ImagebirdDrawinrect:cgrectmake ( Self. BIRDX, Self. BirdY, ImageWidth, ImageHeight)];if( Self. BIRDX<0|| ( Self. BIRDX> Screenwidth-imagewidth)) { Self. Birdspeedx= - Self. Birdspeedx; }if( Self. BirdY<0|| ( Self. BirdY> Screenheight-imageheight)) { Self. Birdspeedy= - Self. Birdspeedy; } Self. BIRDX+= Self. Birdspeedx; Self. BirdY+= Self. Birdspeedy;}
6. The complete code

Here Mrview is the child control of Self.view. Fully covered Self.view

#import "MRView.h" #define ScreenHeight [UIScreen mainscreen].bounds.size.height#define ScreenWidth [UIScreen mainscreen].bounds.size.width#define ImageWidth#define ImageHeight @interface mrview()@property(nonatomic,Strong)UIImage*imagebird;//Bird's location@property(nonatomic,Assign)CGFloatBIRDX;@property(nonatomic,Assign)CGFloatBirdY;//Bird's speed@property(nonatomic,Assign)CGFloatBirdspeedx;@property(nonatomic,Assign)CGFloatBirdspeedy;@end @implementation mrview - (void) awakefromnib{[ SelfSetupbird];} -(Instancetype) initWithFrame: (CGRect) frame{if( Self= [SuperInitwithframe:frame]) {[ SelfSetupbird]; }return  Self;} -(void) setupbird{ Self. BackgroundColor= [UicolorBlackcolor]; Cadisplaylink *link = [Cadisplaylink displaylinkwithtarget: SelfSelector@selector(Setneedsdisplay)]; [link Addtorunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; Self. Imagebird= [UIImageimagenamed:@"Qq20150714-1"];//Set initial position     Self. BIRDX=1; Self. BirdY=1;//Set initial speed     Self. Birdspeedx=5; Self. Birdspeedy=5;} - (void) DrawRect: (CGRect) rect{[ Self. ImagebirdDrawinrect:cgrectmake ( Self. BIRDX, Self. BirdY, ImageWidth, ImageHeight)];if( Self. BIRDX<0|| ( Self. BIRDX> Screenwidth-imagewidth)) { Self. Birdspeedx= - Self. Birdspeedx; }if( Self. BirdY<0|| ( Self. BirdY> Screenheight-imageheight)) { Self. Birdspeedy= - Self. Birdspeedy; } Self. BIRDX+= Self. Birdspeedx; Self. BirdY+= Self. Birdspeedy;}@end
7. Results show

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Physical knowledge application in iOS animations-collision detection

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.