来自 class 的 SpriteKit 调用函数

SpriteKit calling function from class

这是来自 SpriteKit 中的一个简单游戏,其中有一个 Ball() class,它有一个函数 shieldOn(),目前,它只是将单个球的纹理替换为被包围的球的纹理通过盾牌。

球在GameScene中是这样创建的:

func getBall() {
   let ball = Ball()
   ball.createBall(parentNode: self)
}

这是球class

class Ball: SKSpriteNode {

   func createBall(parentNode: SKNode) {
      let ball = SKSpriteNode(texture: SKTexture(imageNamed: "ball2"))
      ball.physicsBody = SKPhysicsBody(circleOfRadius: 25)
      ball.name = "ball"
      parentNode.addChild(ball)
      ball.size = CGSize(width: 50, height: 50)
      ball.position = CGPoint(x: 20, y: 200)

      launch(spriteNode: ball, parentNode: parentNode)
   }


   private func launch(spriteNode: SKSpriteNode, parentNode: SKNode) {
      spriteNode.physicsBody?.applyImpulse(CGVector(dx: 5, dy: 0))
   }

   func shieldOn() {
      self.texture = SKTexture(imageNamed: "ballShield")
   }

   func shieldOff() {
      self.texture = SKTexture(imageNamed: "ball2")
   }
}

在我的代码的主要部分 (GameScene.swift) 我没有对球的引用。所以我循环浏览屏幕上的所有节点并尝试投射匹配的节点,如下所示。我崩溃并出现错误,说它无法将类型 SKSpriteNode 的值转换为 Ball。

for node in self.children {
   if node.name == "ball" {
      let ball = node as! Ball
      ball.shieldOn()
   }
 }

我尝试了一些变体,但没有成功。我至少在朝着正确的方向努力吗?谢谢!

也许更好的方法是保留所有已创建并添加到场景中的球的数组。然后你可以遍历你的数组并更新它们的纹理。您不需要在屏幕上枚举它们,如果有很多移动的精灵,这会降低性能。

就您的代码而言,您可能会受到此错误的影响:

https://forums.developer.apple.com/thread/26362

根据新信息,我想你想要这样的东西:

球Class:

class Ball: SKSpriteNode{


init() {

    let texture = SKTexture(imageNamed: "ball2")
    let size = CGSize(width: 50, height: 50)

    super.init(texture: texture, color: UIColor.clear, size: size)

    self.name = "ball"
    self.physicsBody = SKPhysicsBody(circleOfRadius: size.height/2)

    self.physicsBody?.applyImpulse(CGVector(dx: 5, dy: 0))

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

    func shieldOn() {
        self.texture = SKTexture(imageNamed: "ballShield")
    }

    func shieldOff() {
        self.texture = SKTexture(imageNamed: "ball2")
    }

}

然后用这个来创建球:

func getBall() {
    let ball = Ball()
    ball.position = CGPoint(x: 20, y: 200)
    scene?.addChild(ball)
}