如何在场景中生成对象?

时间:2016-12-02 16:29:53

标签: swift sprite-kit swift3

我正在使用NSTimer在我的场景中生成对象。 例如:

var enemyTimer = Timer()

enemyTimer = Timer.scheduledTimer(timeInterval: 0.8, target: self, selector:#selector(GameScene.enemyAppear),userInfo: nil, repeats: true)

但我遇到了一些麻烦。我需要生成没有时间间隔的新对象。我需要生成新节点,它们之间有一定距离。例如,对象之间有150个点。我怎样才能做到这一点? 对不起我的英文......

1 个答案:

答案 0 :(得分:2)

使用for循环并应用一些数学可以轻松解决这个问题。

假设你想要生成5个敌人,每个敌人之间有100个像素,在y = 0的水平线上对齐:

for i in 0..<5 { // repeat 5 times
    let enemy = SKSpriteNode(imageNamed: "insert your texture for the enemy here") // create new enemy
    // here's the math part. When we generate the first enemy, i is 0, so it is at (0, 0). 
    // When it's time for the second enemy, i will be 1, so it will be placed at (100, 0)
    enemy.position = CGPoint(x: 100 * i, y: 0)
    enemy.anchorPoint = CGPoint(x: 0, y: 0)
    self.addChild(enemy)
}

您可能还想将敌人添加到数组中,以便稍后检索它们。