lundi 27 juin 2016

Speed up all sprites in the game


Explanation

I'm trying to speed up my game when touching the screen (and decreasing its speeds when touching again). I kinda made it work, but not fully.
When touching the screen, all actions are removed and ran again (so it can read the new gameSpeed). But the sprites that were already spawned, won't be applied to the new action, so it still runs by the last gameSpeed. Is there any way to make all the sprites be speeded up?


Code

This is the test code I made (you can download it here):

import SpriteKit

class GameScene: SKScene {

    // MARK: - Declare
    lazy var frameHeight : CGFloat = CGFloat(self.frame.height)

    var ball = SKSpriteNode()

    var speeded = Bool()
    var gameSpeed = CGFloat(1)

    // MARK: - Setup
    func setupBall(){

        ball = SKSpriteNode(imageNamed: "ball")
        ball.position = CGPointMake(self.frame.width / 2, self.frame.height)
    }

    // MARK: - Action
    func actionsBall(){

        // Spawn ball
        self.setupBall()
        self.addChild(self.ball)

        // Move down and remove when go off screen
        let duration = (NSTimeInterval((0.003 / gameSpeed) * frameHeight))
        let moveBall = SKAction.moveByX(0, y: -frameHeight, duration: duration)
        let removeBall = SKAction.removeFromParent()

        self.ball.runAction(SKAction.sequence([moveBall, removeBall]))
    }

    // MARK: - First Event
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */

      // Start spawning, moving and removing
      runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration((0.00075 / Double(gameSpeed)) * Double(frameHeight)), SKAction.runBlock(self.actionsBall)])))
    }

    // MARK: - Touch
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */

        if speeded == false{

            speeded = true

            gameSpeed = 2

            removeAllActions()
            runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration((0.00075 / Double(gameSpeed)) * Double(frameHeight)), SKAction.runBlock(self.actionsBall)])))
        }
        else if speeded == true{

            speeded = false

            gameSpeed = 1

            removeAllActions()
            runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration((0.00075 / Double(gameSpeed)) * Double(frameHeight)), SKAction.runBlock(self.actionsBall)])))
        }
    }

    // MARK: - Update
    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */

    }
}


Thanks in advance,
Luiz.


Aucun commentaire:

Enregistrer un commentaire