Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

nstimer - What is the best way to make a bouncing ball animation with infinite loop on iPhone?

I am developing an iPhone game in which birds bounce.

I have set up the images for animating the wings of the flying bird like this:

[imgBird[i] setAnimationImages:birdArrayConstant];
[imgBird[i] setAnimationDuration:1.0];
[imgBird[i] startAnimating];

Now how I make the bird move is to use an NSTimer to fire every 0.03 seconds which adds/subtracts 1 from the x or y coordinate from imgBird[i].center.

I learnt about doing it like this from here. http://icodeblog.com/2008/10/28/iphone-programming-tutorial-animating-a-ball-using-an-nstimer/

But the issue is the birds slow down as soon as another timer (for moving my ship the same way) fires and returns back to original speed as i stop moving the ship.

Is there a better way to keep the bird moving except NSTimer?

The movement of bird is an infinite loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need to import CoreGraphics and the QuartzCore frameworks into you project.

Add these lines to the top of your file.

#import <QuartzCore/QuartzCore.h>
#import <CoreGraphics/CoreGraphics.h>

...

UIImageView *bird = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bird2.png"]];

CALayer *b = bird.layer;

// Create a keyframe animation to follow a path to the projected point

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"scale"];
animation.removedOnCompletion = NO;


// Create the path for the bounces
CGMutablePathRef thePath = CGPathCreateMutable();

// Start the path at my current location
CGPathMoveToPoint(thePath, NULL, bird.center.x, bird.center.y);
CGPathAddLineToPoint(thePath, NULL,20, 500.0);

/*  // very cool path system.
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath,NULL,74.0,74.0);

CGPathAddCurveToPoint(thePath,NULL,74.0,500.0,
                      320.0,500.0,
                      320.0,74.0);
CGPathAddCurveToPoint(thePath,NULL,320.0,500.0,
                      566.0,500.0,
                      566.0,74.0);
*/

//animation.rotationMode = kCAAnimationRotateAuto;

animation.path = thePath;

animation.speed = 0.011;
//animation.delegate = self;
animation.repeatCount = 1000000;

// Add the animation to the layer
[b addAnimation:animation forKey:@"move"];

Hope that helps a bit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...