通过Y - Swift 2 + SpriteKit移动SKSpriteNode

时间:2015-12-25 01:59:51

标签: swift sprite-kit swift2 skspritenode

我正在开发2D游戏,我正在使用Swift和SpriteKit。首先,我开始创建动画对象并向下移动。为了创建这些"对象",我使用了太空飞船(Xcode的资产图像)。

请参阅我的代码:

import SpriteKit

class GameScene: SKScene {

    var spaceship = SKSpriteNode()

    var screenSize:CGSize!

    var gameStarted:Bool = false

    var moveAndRemove = SKAction()

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        screenSize = self.frame.size

        self.createSpaceship()
    }


    func createSpaceship() -> Void {
        spaceship = SKSpriteNode()
        spaceship.texture = SKTexture(imageNamed: "Spaceship")
        spaceship.size = CGSize(width: 70, height: 100)
        spaceship.setScale(1.0)

        spaceship.position = CGPoint(x: screenSize.width / 3, y: screenSize.height - 75)

        spaceship.zPosition = 1

        self.addChild(spaceship)
    }


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if gameStarted == false {
            gameStarted = true

            let spawn = SKAction.runBlock { () in
                self.createSpaceship()
            }
            let delay = SKAction.waitForDuration(1.5)
            let spawnDelay = SKAction.sequence([spawn, delay])
            let spanDelayForever = SKAction.repeatActionForever(spawnDelay)
            self.runAction(spanDelayForever)

            let distance = CGFloat(screenSize.height + spaceship.frame.height)
            let moveTargets = SKAction.moveToY(spaceship.frame.origin.y - distance, duration: 8.0)
            let removeTargets = SKAction.removeFromParent()

            moveAndRemove = SKAction.sequence([moveTargets,removeTargets])
        }
    }

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

但是当我运行游戏时,太空飞船仍在展示中。我发现它无法解决。

有人可以帮助我吗?

太空飞船必须下降(Y),创建副本,然后向下移动到Y.

1 个答案:

答案 0 :(得分:3)

您需要在每艘宇宙飞船上运行moveAndRemove动作。我建议您将操作定义移至createSpaceship方法,并在您创建的每个太空船上运行moveAndRemove操作。例如,

func createSpaceship() {
    // This can be a local variable and combined into a single statement
    let spaceship = SKSpriteNode(imageNamed: "Spaceship")
    spaceship.size = CGSize(width: 70, height: 100)
    spaceship.setScale(1.0)
    spaceship.position = CGPoint(x: screenSize.width / 3, y: screenSize.height - 75)
    spaceship.zPosition = 1

    let distance = CGFloat(screenSize.height + spaceship.frame.height)
    let moveTargets = SKAction.moveToY(spaceship.frame.origin.y - distance, duration: 8.0)
    let removeTargets = SKAction.removeFromParent()
    let moveAndRemove = SKAction.sequence([moveTargets,removeTargets])

    // Add the action to the list of actions executed by the spaceship
    spaceship.runAction(moveAndRemove)

    self.addChild(spaceship)
}