Skip to content

Instantly share code, notes, and snippets.

@jamesnvc
Created October 30, 2015 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesnvc/b8e17061a6e84d96d478 to your computer and use it in GitHub Desktop.
Save jamesnvc/b8e17061a6e84d96d478 to your computer and use it in GitHub Desktop.
SpriteKit update function
-(void)update:(CFTimeInterval)currentTime {
static CFTimeInterval lastObstacleAt = 1;
static CFTimeInterval pausedLoopAt;
if (self.paused) {
if (!pausedLoopAt) {
pausedLoopAt = currentTime;
}
return;
} else if (pausedLoopAt) {
lastObstacleAt += currentTime - pausedLoopAt;
pausedLoopAt = 0;
}
// Corgi sometimes gets stuck hovering...
if (self.corgi.isJumping && self.corgi.physicsBody.isResting) {
// ...so we nudge it a bit so the physics simulator comes back to life.
[self.corgi.physicsBody applyImpulse:CGVectorMake(0, -1)];
}
// Update score
_gameState.score += roundf(0.5 * _gameState.speed);
self.scoreLabel.text = [NSString stringWithFormat:@"%lupts", (unsigned long)_gameState.score];
// Base movement rate for background & obstacles
float xMovement = _gameState.movementRate * _gameState.speed;
// Move background
[_bgSprites enumerateObjectsUsingBlock:^(SKSpriteNode *bgSprite, NSUInteger idx, BOOL *stop) {
// There are two copies of each background layer, offset by 0.5 their width to allow for continuous scrolling
NSUInteger layerIdx = floor(idx / 2.0); // This converts array index to logical layer index
CGPoint bgPos = bgSprite.position;
// The background layers move at different rates to give a parallax effect
bgPos.x -= xMovement * [_layerProcessionRates[layerIdx] floatValue];
if (bgPos.x + bgSprite.size.width / 2.0 <= 0) {
// If the layer has moved off to the left, put it back on the right side so we can keep scrolling
bgPos.x += bgSprite.size.width * 2;
}
bgSprite.position = bgPos;
}];
// Move extant obstacles
[self.foreground enumerateChildNodesWithName:kObstacleNodeName usingBlock:^(SKNode *obs, BOOL *stop) {
obs.position = CGPointMake(obs.position.x - xMovement, obs.position.y);
if (obs.position.x < 0) {
[obs removeFromParent];
}
}];
// Spawn new obstacles
if (currentTime > lastObstacleAt + ((2 + arc4random() % 5) / _gameState.speed)) {
SKSpriteNode *obstacle = [sharedObstacle copy];
obstacle.position = CGPointMake(CGRectGetMaxX(self.frame) - obstacle.size.width / 2,
_groundTop + obstacle.size.height);
[self.foreground addChild:obstacle];
lastObstacleAt = currentTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment