随机x位置问题

时间:2015-01-28 06:50:27

标签: objective-c position sprite-kit

我每隔几秒就有一个圆圈产生,我有五个通道,我希望它们能够产生,但是我想让它随机地转到另一个。我正在使用的代码工作正常,但它不会让我使用我的五个x位置?我尝试了多种解决方案,但它们无法正常工作。我仍然是新的目标c所以任何帮助将不胜感激。 (另外,下面的代码显然不是我的整个方法,但它是我需要展示的唯一部分。)

#import "GameScene.h"

int xPos1;
int xPos2;
int xPos3;
int xPos4;
int xPos5;

@implementation GameScene

-(void) addBall:(CGSize) size{
xPos1 = 8.5;
xPos2 = 74;
xPos3 = 138;
xPos4 = 203;
xPos5 = 267.5;

CGRect box = CGRectMake( arc4random()  , self.frame.size.height,    //pos
                        45, 45);   //size
UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:box];

SKShapeNode *circle = [SKShapeNode node];
circle.path = circlePath.CGPath;
circle.fillColor = [SKColor colorWithRed:(243.0f/255) green:(134.0f/255) blue:(48.0f/255) alpha:1.0];
circle.strokeColor = nil;
circle.lineWidth = 3;

//add physics
circle.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:circle.frame.size.width/2];

//appy actions to move sprite
SKAction *wait = [SKAction waitForDuration:2];
SKAction *move = [SKAction moveToY:-self.size.height - 50 duration:2];
SKAction *remove = [SKAction removeFromParent];
SKAction *sequence = [SKAction sequence:@[wait, move, remove]];
SKAction *repeat = [SKAction repeatActionForever:sequence];

SKAction *spawn = [SKAction performSelector:@selector(addBall:) onTarget:self];
SKAction *delay = [SKAction waitForDuration:2.5];
SKAction *spawnThenDelay = [SKAction sequence:@[delay, spawn]];


[self runAction:spawnThenDelay];
[circle runAction:repeat];
[self addChild:circle];

}

以下是我尝试使用arc4random中的x位置的不同内容:

CGRect box = CGRectMake( arc4random() %(xPos1, xPos2, xPos3, xPos4, xPos5)  , self.frame.size.height,    //pos
                        45, 45);

CGRect box = CGRectMake( arc4random(xPos1, xPos2, xPos3, xPos4, xPos5)  , self.frame.size.height,    //pos
                        45, 45);

我也尝试过将整数直接放在那里......

1 个答案:

答案 0 :(得分:2)

尝试创建一个X位置数组,并使用随机索引从中进行选择。

CGFloat xPositions[5] = {8.5,74,138,203,267.5};

int randomIndex = arc4random() % 5;
int randomXPosition = xPositions[randomIndex]

CGRect box = CGRectMake(randomXPosition, self.frame.size.height, 45, 45);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:box];