[英]Making a sprite move randomly across the screen
我正在制作2D游戲,其中我需要一個精靈實例來隨機飛過屏幕。 它們會隨機生成,剛好超出iPhone屏幕的邊界,然后在屏幕內移動。 當它們碰到邊緣時,它們會重新出現在另一側。 我需要知道的是如何讓精靈隨機移動。
將此方法添加到您的圖層類中-它會吸收一個精靈,然后永遠在屏幕上隨意移動它:
-(void)moveRandom:(CCSprite*)s
{
CGPoint randomPoint = ccp(arc4random()%480, arc4random()%320);
NSLog(@"%@", NSStringFromCGPoint(randomPoint));
[s runAction:
[CCSequence actions:
[CCMoveTo actionWithDuration:arc4random()%5+1 position: randomPoint],
[CCCallBlock actionWithBlock:^{
[self performSelector:@selector(moveRandom:) withObject:s afterDelay:0.5];
}],
nil]
];
}
如您所見,這非常簡單-在屏幕上生成一個隨機點,然后在精靈上運行移動動作到該點。 完成后-重復一遍。
要在屏幕上添加精靈並開始該過程,請將其(可能)放入場景init方法或場景初始化的任何地方:
CCSprite* s = [CCSprite spriteWithFile:@"yourImage.png"];
[self addChild: s];
[self moveRandom:s];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.