【问题标题】:Adding life sprites in SpriteKit with Swift使用 Swift 在 SpriteKit 中添加生命精灵
【发布时间】:2015-08-04 02:43:32
【问题描述】:

我正在构建我的第一个 swift 游戏,但我在为玩家实现生活时遇到了困难。它应该在不同的屏幕位置显示三个生命,就像一个微型图像......我知道 for 循环可以完成这项工作,但我不知道如何编写它。当我尝试使用 addChild(LifeIndex) 将相同的精灵添加到屏幕时,它会引发错误。

下面是代码:

  // Add Life to player

    let lifeIndex = SKSpriteNode(imageNamed: "bullet.png")

    var lifeCount = 3

    lifeIndex.position = CGPoint(x: self.frame.size.width * -1.5, y: self.frame.size.height * 0.1)

    let lifeIndexMove = SKAction.moveTo(CGPoint(x: size.width * 0.1, y: size.height * 0.1), duration: NSTimeInterval(0.7))

    let lifeIndexRotation = SKAction.rotateByAngle(CGFloat(-2 * M_PI), duration: 0.3)

    addChild(lifeIndex)

    lifeIndex.runAction(SKAction.sequence([lifeIndexMove, lifeIndexRotation]))

我怎样才能做到三遍?另外,我需要将不同的点放入 moveTo 中,以便它们可以并排,而不是彼此重叠。

【问题讨论】:

  • 将所有这些放在循环 lifeCount 次数的 for 循环中。 lifeIndexMove 和 lifeIndexRotation 对于这三个都一样吗?
  • lifeIndexRotation 将是相同的,但我需要在 lifeIndexMove 的 x 参数中增加一个增量,以便它可以与其他精灵并排。

标签: swift sprite-kit


【解决方案1】:

试试这个:

    // Add Life to player

    var lifeIndexCount = 0
    var positionAdd:CGFloat = 10.0

    for lifeIndexCount in 0..<3 {

        let lifeIndex = SKSpriteNode(imageNamed: "bullet.png")

        lifeIndex.position = CGPoint(x: self.frame.size.width * -1.5, y: self.frame.size.height * 0.1)

        let lifeIndexMove = SKAction.moveTo(CGPoint(x: (size.width * 0.1) + positionAdd, y: size.height * 0.1), duration: NSTimeInterval(0.7))

        let lifeIndexRotation = SKAction.rotateByAngle(CGFloat(-2 * M_PI), duration: 0.3)

        lifeIndex.runAction(SKAction.sequence([lifeIndexMove, lifeIndexRotation]))

        addChild(lifeIndex)

        positionAdd = positionAdd + 30.0

    }

【讨论】:

  • 编译错误很少,但很容易解决。最大的问题是 addChild(lifeIndex) 引发错误。
  • 更新的代码尝试在循环内移动 var lifeIndex = SKSpriteNode(imageNamed: "bullet.png")。如果这不起作用,我将删除答案,直到我可以正确测试我建议的答案
  • 同样的编译错误和 lifeIndex 需要是一个 let 类型,但是是的,解决了 addChild 方法崩溃的主要问题。谢谢!
  • 您是否会更新答案中的语法错误以确保完整性。谢谢!
【解决方案2】:

您不能像这样简单地创建三个nodes 并定位第一个:

lifeIndex.position = CGPoint(x: self.frame.size.width * -1.5, y: self.frame.size.height * 0.1)

第二个

lifeIndex2.position = CGPoint(x: self.frame.size.width * -1.5 + lifeIndex2.size.width * 1.5, y: self.frame.size.height * 0.1)

第三个

lifeIndex3.position = CGPoint(x: self.frame.size.width * -1.5 + lifeIndex2.size.width * 3, y: self.frame.size.height * 0.1)

我认为这应该将它们放在彼此旁边。

我认为你这样做更简单,而不是创建一个 func 并产生三个相似的节点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多