使精灵在屏幕上随机移动 [英] Making a sprite move randomly across the screen

查看:33
本文介绍了使精灵在屏幕上随机移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个 2d 游戏,其中我需要一个精灵实例在屏幕上随机飞行.它们会在 iPhone 屏幕边界之外随机生成,然后在屏幕内移动.当它们碰到边缘时,它们会出现在另一侧.我只需要知道如何让精灵随机移动.

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

这篇关于使精灵在屏幕上随机移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆