加速游戏中的所有精灵

时间:2016-06-26 16:53:15

标签: ios swift sprite-kit

说明

我试图在触摸屏幕时加速我的游戏(并在再次触摸时降低速度)。我有点工作,但不完全。
当触摸屏幕时,所有操作都将被删除并再次运行(因此它可以读取新的gameSpeed)。但是已经产生的精灵不会被应用于新动作,所以它仍然在最后gameSpeed运行。有没有办法让所有的精灵加速?


代码

这是我制作的测试代码(您可以下载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 */

    }
}


提前谢谢,
路易斯。

1 个答案:

答案 0 :(得分:0)

在SKScene类的didMove方法中,添加以下内容:

physicsWorld.speed = CGFloat(2.0)

很可能你只是没有将其作为CGFloat传递,或者它没有包含在正确的方法中。