0

I am having a lot of trouble with making my app randomly choose between two actions and then repeating the actions every half a second.

Here is my code:

    //Setting the sprite to a position on the screen (it happens to be right where the  screen cuts off)
    SKSpriteNode *lightnut = [SKSpriteNode spriteNodeWithImageNamed:@"lightnut.png"];
    lightnut.position = CGPointMake(257,510);
    [self addChild: lightnut];

    //The action that makes the sprite move to the new part of the screen
    SKAction *moveNodeUp = [SKAction moveByX:0.0 y:-600.0 duration:2.0];
    [lightnut runAction: moveNodeUp];

I want my app to either choose to set the sprite at (257,510) or (150, 510).

For example:

    SKSpriteNode *lightnut = [SKSpriteNode spriteNodeWithImageNamed:@"lightnut.png"];
    lightnut.position = CGPointMake(257,510);
    OR
    lightnut.position2 = CGPointMake (150,510);
    [self addChild: lightnut];

    SKAction *moveNodeUp = [SKAction moveByX:0.0 y:-600.0 duration:2.0];
    [lightnut runAction: moveNodeUp];

If anyone can help with that it would be great!

Also, I don't really understand this but I am still trying to figure it out. Is there a way to refresh the action (so that my app would keep randomly choosing between the two points and letting them move to the new position) even before the action before hasn't finished, making it send a new sprite before the other one has even left the screen? Thanks!

Ryandev
  • 91
  • 5

1 Answers1

2

To get a random, uniformly distributed, you can use arc4random_uniform() (see e.g. here).

A coin flip would look like this:

BOOL heads = arc4random_uniform(100) < 50;

You probably know what to do next, like:

lightnut.position = (heads)? CGPointMake(257,510) : CGPointMake(150,510);
Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136
  • Thanks for the explanation! I think I learned about that but I did not understand how to put my code and that together. Thank you for making it easier! – Ryandev Oct 06 '14 at 23:24