添加SpriteNodes并根据时间删除或使用SpriteKit单击

时间:2016-04-27 15:42:39

标签: swift sprite-kit sprite skspritenode

我是新手,希望能够建立我的第一个基本游戏。我想到的游戏涉及随机生成的精灵,然后根据时间或点击消失,如果点击在分配的时间内。到目前为止,我已经创建了基本框架,并且仍在忙于设计。我的问题来自于我似乎无法根据时间删除精灵(它生成正常)。任何帮助表示赞赏,并提前感谢

以下是我到目前为止建立的框架。

 import SpriteKit

var one = SKSpriteNode()

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */       

        let myFunction = SKAction.runBlock({()in self.addOne()})
        let wait = SKAction.waitForDuration(5)
        let remove = SKAction.runBlock({() in self.removeOne()})

        self.runAction(SKAction.sequence([myFunction, wait, remove]))


    }

    func addOne() {

        let oneTexture = SKTexture(imageNamed: "blue button 10.png")

        let one = SKSpriteNode(texture: oneTexture)

        one.position = CGPoint(x: CGRectGetMidX(self.frame) - 100, y: CGRectGetMidY(self.frame) + 250)
        one.zPosition = 1

        self.addChild(one)


    }

    func removeOne() {

        one.removeFromParent()

    }

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

    }

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

    }
}

1 个答案:

答案 0 :(得分:1)

它不会消失,因为你创建了一个新的SpiteNode,但尝试删除旧的SpiteNode,就这样做:

    var one : SKSpriteNode! //instead of creating it without data, just define the type(not necessary, but I would do it)

    class GameScene: SKScene {
        override func didMoveToView(view: SKView) {
            /* Setup your scene here */

            let myFunction = SKAction.runBlock({()in self.addOne()})
            let wait = SKAction.waitForDuration(5)
            let remove = SKAction.runBlock({() in self.removeOne()})

            self.runAction(SKAction.sequence([myFunction, wait, remove]))


        }

        func addOne() {

            let oneTexture = SKTexture(imageNamed: "blue button 10.png")

            one = SKSpriteNode(texture: oneTexture) //removed the let, so you dont create a new "one"

            one.position = CGPoint(x: CGRectGetMidX(self.frame) - 100, y: CGRectGetMidY(self.frame) + 250)
            one.zPosition = 1

            self.addChild(one)


        }

        func removeOne() {

            one.removeFromParent()

        }
}