【问题标题】:In swift, is there a way to select a sprite by its name?迅速,有没有办法通过它的名字来选择一个精灵?
【发布时间】:2016-12-15 01:15:12
【问题描述】:

我是 Swift 编码的新手,所以如果这是一个愚蠢的问题,我深表歉意。

我有一个创建一系列 Sprite 的函数。这些精灵四处移动并改变大小。通过该函数,每一个都被赋予了一个唯一的名称。

我想做的是在用户按下一组单独的精灵时改变它们的位置/动画/大小/纹理。换句话说,我需要按下另一个精灵来调用一个改变第一组精灵的函数。

但是,我在执行此操作时遇到了麻烦。如果我硬连线精灵的特定变量名,似乎我可以让它工作。但是,因为有很多,它们可能会随着时间而改变,我可能想循环通过其中的许多硬连线不好。

基本上,我希望能够选择一个精灵并在触摸另一个精灵时为其设置动画。

有什么建议吗?

【问题讨论】:

  • 从精灵的String 名称创建字典到精灵实例
  • 制作你自己的 Skspritenode(子类)并覆盖它的 touchesBegan。制作一个初始化婴儿车,其中触摸将动画的精灵。如果你需要,我可以回答。

标签: swift sprite-kit sprite


【解决方案1】:

您可以创建自己的 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)
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-16
    • 2019-09-06
    • 1970-01-01
    • 2022-09-27
    • 2020-07-11
    • 2017-07-03
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多