你可以创建自己的 SKSpriteNode 子类,然后通过对象名称(变量或常量名)调用它们。这意味着你不必硬编码,并且可以使用任何逻辑/函数来更改动画或所调用/使用的精灵名称等。
在此演示中,我创建了两个对象...一个是电灯泡,另一个是开关。当你点击开关时,电灯泡会亮起来。
阅读注释以了解如何自定义此功能。您可以让任何对象告诉任何其他精灵播放它们的个人动画:
class TouchMeSprite: SKSpriteNode {
var personalAnimation: SKAction?
var othersToAnimate: [TouchMeSprite]?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let sprites = othersToAnimate else {
print("No sprites to animate. Error?")
return
}
for sprite in sprites {
if sprite.scene == nil {
print("sprite was not in scene, not running animation")
continue
}
guard let animation = sprite.personalAnimation else {
print("sprite had no animation")
continue
}
sprite.run(animation)
}
}
}
这是展示灯开关和灯泡演示的GameScene文件:
class GameScene: SKScene {
override func didMove(to: SKView) {
let lightBulb = TouchMeSprite(color: .black, size: CGSize(width: 100, height: 100))
lightBulb.personalAnimation = SKAction.colorize(with: .yellow, colorBlendFactor: 1, duration: 0)
lightBulb.position = CGPoint(x: 0, y: 400)
lightBulb.isUserInteractionEnabled = true
addChild(lightBulb)
let lightSwitch = TouchMeSprite(color: .gray, size: CGSize(width: 25, height: 50))
lightSwitch.othersToAnimate = [lightBulb]
lightSwitch.isUserInteractionEnabled = true
lightSwitch.position = CGPoint(x: 0, y: 250)
addChild(lightSwitch)
}
}