在Swift中,有没有一种方法可以通过名称选择精灵?

3
我刚开始学习Swift编程,如果我问了一个愚蠢的问题,请见谅。
我有一个函数,用于创建一系列精灵。这些精灵会移动并改变大小。通过该函数,每个精灵都有一个独特的名称。
我想要的是在用户按下另一组精灵时更改它们的位置/动画/大小/纹理。换句话说,我需要按下另一个精灵来调用一个函数,它会改变第一组精灵。
但是,我做不到这一点。似乎只有将一个特定精灵的变量名硬编码才能使其正常工作。然而,由于有很多精灵,它们可能随着时间的推移而改变,我可能想要循环遍历其中的许多精灵,硬编码并不好用。
基本上,我想要能够选择一个精灵并在触摸到另一个精灵后对其进行动画处理。
有什么建议吗?

创建一个从精灵的“String”名称到精灵实例的字典。 - Alexander
制作自己的Skspritenode(子类),并覆盖其touchesBegan方法。创建一个初始化参数,用于指定触摸将要动画化的精灵。如果需要,我可以提供答案。 - Fluidity
1个回答

1
你可以创建自己的 SKSpriteNode 子类,然后通过对象名称(变量或常量名)调用它们。这意味着你不必硬编码,并且可以使用任何逻辑/函数来更改动画或所调用/使用的精灵名称等。
在此演示中,我创建了两个对象...一个是电灯泡,另一个是开关。当你点击开关时,电灯泡会亮起来。
阅读注释以了解如何自定义此功能。您可以让任何对象告诉任何其他精灵播放它们的个人动画:
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)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接