Swift 3重复产生SKNode

时间:2016-10-16 20:52:40

标签: swift sprite-kit

我有一个SKNode产生并在屏幕上移动。这一切都按预期工作。但是,我不确定如何多次出现这种情况。我的愿望是'桶'每2秒产卵一次。您可以在下面的代码中看到我的尝试。

class GameScene : SKScene, SKPhysicsContactDelegate {

var Player = SKSpriteNode()
var Ground = SKSpriteNode()
var Roof = SKSpriteNode()
var Background = SKSpriteNode()
let Obstacle1 = SKSpriteNode(imageNamed: "Fire Barrel 1")

override func didMove(to view: SKView) {

    // Create Background Color
    backgroundColor = bgColor

    // Set World Gravity
    self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -4.0)

    // Create Player
    Player = SKSpriteNode(imageNamed: "Player")
    Player.setScale(0.5)
    Player.position = CGPoint(x: -self.frame.width / 2 + 100, y: -Player.frame.height / 2)

    self.addChild(Player)

    // Create Ground
    Ground = SKSpriteNode(imageNamed: "BGTileBtm")
    Ground.anchorPoint = CGPoint(x: 0,y: 0.5)
    Ground.position = CGPoint(x: -self.frame.width / 2, y: -self.frame.height / 2)

    self.addChild(Ground)

    // Create Roof
    Roof = SKSpriteNode(imageNamed: "BGTileTop")
    Roof.anchorPoint = CGPoint(x: 1,y: 1)
    Roof.position = CGPoint(x: -self.frame.width / 2, y: self.frame.height / 2 - Roof.frame.height)
    Roof.zRotation = CGFloat(M_PI)

    self.addChild(Roof)

    // Set Physics Rules
    Player.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Player"), size: Player.size)
    Player.physicsBody!.affectedByGravity = true
    Player.physicsBody!.allowsRotation = false

    Ground.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Ground"), size: Ground.size)
    Ground.physicsBody!.affectedByGravity = false
    Ground.physicsBody!.isDynamic = false

    // Obstacle
    func addObstacle1(){

        Obstacle1.position = CGPoint(x: self.frame.width / 2, y: -self.frame.height / 2 + Obstacle1.frame.height)
        Obstacle1.zPosition = 1
        addChild(Obstacle1)

        let distance = CGVector(dx: -self.frame.width, dy: 0)
        let moveDistance = SKAction.move(by: distance, duration: 5)
        Obstacle1.run(moveDistance)

    }

    let spawnObstacles = SKAction(addObstacle1())
    let delay = SKAction.wait(forDuration: 2)
    let sequence = SKAction.sequence([delay, spawnObstacles])

    run(SKAction.repeatForever(sequence))

}

1 个答案:

答案 0 :(得分:0)

首先将addObstacle放在didMove方法之外。然后在didMove方法中添加以下内容:

_ = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(addObstacle1), userInfo: nil, repeats: true)

它应该每两秒重复一次addObstacle:)