2011-05-20 290 views
0

我在Cocos2d上做遊戲。我想讓敵人在屏幕的右側和左側產生,並移動到屏幕上的隨機點,然後重複。儘管我的努力,我無法弄清楚。這應該相對容易回答,它應該看起來像Ray Wenderlich的教程之一。一些代碼會很好。謝謝!Cocos2d問題/問題

回答

1

這是從射線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刪除精靈。