0

i'm building a game for which i the gravity as:

self.physicsworld.gravity = CGVectorMake(gravityX , gravity-Y);

i want to change the forces acting on the sprite node with time.

since i'm a newbie, i'm not able to code a loop(s) so that the gravity changes over time thereby changing the difficulty of the game. if i want the float variable gravityX to increment by 0.5 every 5 seconds what should be the code implemented.

the main problem i'm facing with using the FOR LOOP here is in the CONDITION; I don't know how to make the computer understand actual time since the game started.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • possible duplicate of [Spritekit - Creating a timer](http://stackoverflow.com/questions/23978209/spritekit-creating-a-timer) - use the timing methods provided by Sprite Kit, **do not** use NSTimer! – CodeSmile Nov 09 '14 at 10:05

1 Answers1

0

This can be done using the SKAction class. Add the following method to your SKScene subclass, and call it when you want gravity to start increasing. I've included both the Objective-C and the Swift version.

Objective-C:

- (void)startGravityIncrease {
    SKAction *blockAction = [SKAction runBlock:^{
        CGVector gravity = self.physicsWorld.gravity;
        gravity.dx += 0.5;
        self.physicsWorld.gravity = gravity;
    }];
    SKAction *waitAction = [SKAction waitForDuration:5];
    SKAction *sequenceAction = [SKAction sequence:@[waitAction, blockAction]];
    SKAction *repeatAction = [SKAction repeatActionForever:sequenceAction];

    [self runAction:repeatAction];
}

Swift:

func startGravityIncrease() {
    let blockAction = SKAction.runBlock { () -> Void in
        self.physicsWorld.gravity.dx += 0.5
    }
    let waitAction = SKAction.waitForDuration(5)
    let sequenceAction = SKAction.sequence([waitAction, blockAction])
    let repeatAction = SKAction.repeatActionForever(sequenceAction)

    self.runAction(repeatAction)
}
Andrew Knoll
  • 211
  • 2
  • 7