1

我正在开发一款让鸟类弹跳的 iPhone 游戏。

我已经设置了像这样为飞鸟的翅膀设置动画的图像:

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

现在我如何让鸟移动是使用 NSTimer 每 0.03 秒触发一次,它从 imgBird[i].center 的 x 或 y 坐标中加/减 1。

我从这里学会了这样做。http://icodeblog.com/2008/10/28/iphone-programming-tutorial-animating-a-ball-using-an-nstimer/

但问题是,一旦另一个计时器(用于以相同方式移动我的船)触发并在我停止移动船时返回原始速度,鸟儿就会减速。

除了 NSTimer 之外,有没有更好的方法让鸟儿保持移动?

鸟的运动是一个无限循环。

4

3 回答 3

4

您需要将 CoreGraphics 和 QuartzCore 框架导入到您的项目中。

将这些行添加到文件的顶部。

#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"];

希望有点帮助。

于 2009-07-01T13:08:13.147 回答
1

从您的问题来看,您似乎使用了多个计时器。仅使用一个即可为所有对象设置动画。在某个地方,当你的应用程序启动时,有这个:

[NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(mainLoop:) userInfo:nil repeats:YES];

然后,在主循环中,是这样的:

- (void)mainLoop:(NSTimer *)timer
{
    // compute new position for imgBirds
    for (int i=0; i<kBirdCount; i++)
    {
        imgBirds[i].center = CGPointMake(somex, somey);
    }

    // compute new position for ship
    ship.center = CGPointMake(somex, somey);
}

此外,您应该计算somexsomey作为计时器间隔的函数。这样,如果你改变它,你的动画看起来还是一样的。

于 2009-06-27T21:53:17.720 回答
0

你会想要使用核心动画而不是手动移动小鸟。查看文档中的CAAnimation。你基本上设置了一个动画,你希望它移动的路径,然后告诉它运行。它会照顾其余的。它还支持宽松,这将使步伐放缓和加快,因此看起来更自然。

于 2009-06-27T14:32:08.853 回答