简体   繁体   中英

Making a sprite move randomly across the screen

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM