垂直动画精灵

时间:2014-03-16 09:07:18

标签: ios animation cocos2d-iphone ccsprite

我遇到一个真正的麻烦,让精灵在顶部的屏幕上产生,然后从顶部到底部动画。我一直在关注Ray Wenderlich关于创建一个简单游戏的教程,然而将精灵从右向左移动,我希望它从上到下移动,现在我非常困难!以下是我目前的代码:

- (void)addComet:(CCTime)dt
{
    // Make sprite
    CCSprite *comet = [CCSprite spriteWithImageNamed:@"PlayerSprite.png"];

    // Verticle spawn range
    int minY = comet.contentSize.width;
    int maxY = self.contentSize.height - comet.contentSize.height / 2;
    int rangeY = maxY - minY;
    int randomY = (arc4random() % rangeY) + minY;

    // Position comets slightly off the screen
    comet.position = CGPointMake(self.contentSize.width + comet.contentSize.width, randomY);
    [self addChild:comet];

    // Duration range comets take to fly across screen
    int minDuration = 2.0;
    int maxDuration = 4.0;
    int rangeDuration = maxDuration - minDuration;
    int randomDuration = (arc4random() % rangeDuration) + minDuration;

    // Give comet animation
    CCAction *actionMove = [CCActionMoveTo actionWithDuration:randomDuration position:CGPointMake(0, 500)];
    CCAction *actionRemove = [CCActionRemove action];
    [comet runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]];
}

如果有人能指出我正确的方向,因为我已经坚持了很长一段时间,并且无法让精灵在屏幕顶部随机生成,然后动画到底部。我也看过像tweejump这样的示例代码,但没有运气。

1 个答案:

答案 0 :(得分:0)

现在,我的任何项目中都没有Cocos2D,所以不知道是否有任何拼写错误,但通常它应该看起来像下面的东西。这个想法是所有的彗星都应该从相同的 Y位置(屏幕外)开始,但是有一个随机的水平(x)位置......

- (void)addComet:(CCTime)dt
{
    // Make sprite
    CCSprite *comet = [CCSprite spriteWithImageNamed:@"PlayerSprite.png"];

    NSInteger y = self.contentSize.height; // perhaps + comet.contentSize.height / 2, if the anchorPoint is 0.5, 0.5

    // Random horizontal position
    NSInteger maxX = self.contentSize.width;
    NSInteger randomX = (arc4random() % maxX);

    // Position comets slightly off the screen
    comet.position = CGPointMake(randomX, y);
    [self addChild:comet];

    // Duration range comets take to fly across screen
    NSInteger minDuration = 2.0;
    NSInteger maxDuration = 4.0;
    NSInteger rangeDuration = maxDuration - minDuration;
    NSInteger randomDuration = (arc4random() % rangeDuration) + minDuration;

    // Give comet animation
    CCAction *actionMove = [CCActionMoveTo actionWithDuration:randomDuration position:CGPointMake(randomX, 0)]; // Moving it in a straight line vertically
    CCAction *actionRemove = [CCActionRemove action];
    [comet runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]];
}