Cocos2d问题/问题

时间:2011-05-20 00:29:49

标签: iphone xcode cocos2d-iphone

我在Cocos2d制作游戏。我希望敌人在屏幕的右侧和左侧产生,并移动到屏幕上的随机点,然后重复。尽管我付出了努力,但我无法弄明白。这应该相对容易回答,它应该看起来像Ray Wenderlich的教程之一。有些代码会很好。谢谢!

1 个答案:

答案 0 :(得分:1)

这是来自Ray Wanderlich教程的代码..

[self schedule:@selector(addTarget) interval:2.0];

-(void)addTarget {

  CCSprite *target = [CCSprite spriteWithFile:@"Target.jpg"  
    rect:CGRectMake(0, 0, 27, 40)]; //Creating Sprite and setting rect

  // Determine where to spawn the target along the Y axis
  CGSize winSize = [[CCDirector sharedDirector] winSize]; //Get the screensize
  int minY = target.contentSize.height/2;
  int maxY = winSize.height - target.contentSize.height/2;
  int rangeY = maxY - minY;
  int actualY = (arc4random() % rangeY) + minY;

  // Create the target slightly off-screen along the right edge,
  // and along a random position along the Y axis as calculated above
  target.position = ccp(winSize.width + (target.contentSize.width/2), actualY);
  [self addChild:target];

  // Determine speed of the target
  int minDuration = 2.0;
  int maxDuration = 4.0;
  int rangeDuration = maxDuration - minDuration;
  int actualDuration = (arc4random() % rangeDuration) + minDuration;

  // Create the actions
  id actionMove = [CCMoveTo actionWithDuration:actualDuration 
    position:ccp(-target.contentSize.width/2, actualY)];
  id actionMoveDone = [CCCallFuncN actionWithTarget:self 
    selector:@selector(spriteMoveFinished:)];
  [target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];

}

minY - >位于屏幕底部的位置 maxY --->位于屏幕顶部的位置。 rangeY --->屏幕的高度。 actualY --->计算屏幕底部和屏幕顶部之间的随机点。

target.position - >设置精灵移动的随机位置。

actualDuration - >获得随机持续时间。因此精灵会以不同的时间延迟移动。

actionMove - >创建Move动作。 actionMoveDone --->完成移动操作后,调用spriteMoveFinished来删除sprite。