您可以创建自己的 SKSpriteNode 子类,然后从它们的对象名(变量名或 let 常量名)调用它们。这意味着您不必硬连线,您可以使用任何类型的逻辑/函数来更改动画或调用/使用的精灵的名称等。
在这个演示中,我制作了两个对象……一个是灯泡,另一个是电灯开关。当你点击灯开关时,灯泡就会亮起来。
阅读 cmets 以了解如何自定义它。您可以让任何对象告诉任何其他精灵播放他们的个人动画:
class TouchMeSprite: SKSpriteNode {
// This is used for when another node is pressed... the animation THIS node will run:
var personalAnimation: SKAction?
// This is used when THIS node is clicked... the below nodes will run their `personalAnimation`:
var othersToAnimate: [TouchMeSprite]?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Early exit:
guard let sprites = othersToAnimate else {
print("No sprites to animate. Error?")
return
}
for sprite in sprites {
// Early exit:
if sprite.scene == nil {
print("sprite was not in scene, not running animation")
continue
}
// Early exit:
guard let animation = sprite.personalAnimation else {
print("sprite had no animation")
continue
}
sprite.run(animation)
}
}
}
这是展示电灯开关和灯泡演示的 GameScene 文件:
class GameScene: SKScene {
override func didMove(to: SKView) {
// Bulb:
let lightBulb = TouchMeSprite(color: .black, size: CGSize(width: 100, height: 100))
// Lightbulb will turn on when you click lightswitch:
lightBulb.personalAnimation = SKAction.colorize(with: .yellow, colorBlendFactor: 1, duration: 0)
lightBulb.position = CGPoint(x: 0, y: 400)
lightBulb.isUserInteractionEnabled = true
addChild(lightBulb)
// Switch:
let lightSwitch = TouchMeSprite(color: .gray, size: CGSize(width: 25, height: 50))
// Lightswitch will turn on lightbulb:
lightSwitch.othersToAnimate = [lightBulb]
lightSwitch.isUserInteractionEnabled = true
lightSwitch.position = CGPoint(x: 0, y: 250)
addChild(lightSwitch)
}
}