Making a sprite move randomly across the screen

╄→尐↘猪︶ㄣ 提交于 2019-12-11 05:36:23

问题


I'm making a 2d Game, in which I need instances of a sprite to fly randomly across the screen. They will spawn in randomly just beyond the boundaries of the iPhone screen, then move within the screen. When they hit the edges, they will appear back on the other side. All I need to know is how to get the sprite to move randomly.


回答1:


Add this method to your layer class - it takes in a sprite and then moves it randomly around the screen for ever:

-(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]
     ];
}

As you can see it's pretty easy - generate a random point on the screen and then run move action on the sprite to that point. When that's done - just repeat.

To add a sprite on the screen and start the process, put this (probably) in your scene init method or wherever you do the scene initialization:

CCSprite* s = [CCSprite spriteWithFile:@"yourImage.png"];
[self addChild: s];
[self moveRandom:s];


来源:https://stackoverflow.com/questions/9225747/making-a-sprite-move-randomly-across-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!