【问题标题】:How to generate objects on scene?如何在场景中生成物体?
【发布时间】:2016-12-02 16:29:52
【问题描述】:

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

var enemyTimer = Timer()

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

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

【问题讨论】:

  • 您可能想要使用 SKAction 来生成敌人,因为 NSTimer 没有与游戏循环配对。因此,例如,如果用户接到电话,当他在游戏中返回时,您的屏幕将充满敌人。当然,您可以监听通知并适当地使 NSTimer 无效/重新启动,但这是通过 SKActions(或 update: 方法)自动完成的。

标签: swift sprite-kit swift3


【解决方案1】:

使用 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)
}

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

【讨论】:

  • 您好!感谢您的回答。我想从屏幕外创建新​​节点。例如:enemy.size = CGSize(x:160, y:80)enemy.position = CGPoint (x:250,y:1200)(我的场景大小 = 768x1024),敌人会移动到 y:-100。我需要他们之间有一些距离。你能帮忙吗?谢谢!
  • @NexusS。您不需要屏幕外精灵之间的距离!用户无论如何都看不到它们。只需每 x 秒向下移动每个 Sprite。这会让精灵看起来像在它们之间有空格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
  • 2011-12-08
  • 2017-11-14
  • 1970-01-01
相关资源
最近更新 更多