首页 > 解决方案 > SWIFT SpriteKit:如何使用 SKnode 的 userData 属性来减少其中的键值?

问题描述

大家好(第一次在这里提问!),

我目前正在尝试使用 SkNode 的“userData”属性来跟踪某个值。在下面的代码中,您可以看到我创建了一个节点调用流星并使用 userData 定义一个带有“健康”的字典值为 3。

meteor = SKSpriteNode(imageNamed: "Meteor")
meteor.name = "meteor"
meteor.userData = NSMutableDictionary()
meteor.userData = ["health" : 3]

此功能会在我触摸屏幕的任何位置创建区域爆炸

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches {
            canonBlastProperties(atPoint: t.location(in: self))
            cannonBlast(delay: 0.001)
        }
}

这个功能允许区域爆炸和我创建的流星之间的接触,这也是我遇到的问题。

func didBegin(_ contact: SKPhysicsContact) {
        var firstBody, secondBody: SKPhysicsBody
        if contact.bodyA.node?.name == "meteor" {
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        }
        else
        {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }
        if firstBody.node?.name == "meteor" && secondBody.node?.name == "blast" {
            firstBody.node?.userData?[.value(forKey: "health")] -= 1
//            score += meteorScore
            print("Detected Contact")
        }
}

更准确地说,这里的这条线是我遇到问题的地方。从技术上讲,每当您触摸屏幕时,每次它与区域爆炸接触时,我都会尝试将特定的流星“健康”减少 1。

firstBody.node?.userData?[.value(forKey: "health")] -= 1

现在,SWIFT 给了我这个错误

Binary operator '-=' cannot be applied to operands of type 'Any?' and 'Int'

所以,我从这个错误中了解到,如果我错了,请纠正我,Swift 不允许我减少“health”的值,因为它的类型是“Any?”。

所以我尝试强制转换类型“任何?” 进入“Int”。从中得到另一个错误。

我似乎有其他人有类似的问题,但他们得到的答案并不能真正适用于我的问题。

我知道 userData 用于在特定节点内存储数据(我已阅读 swift 文档)

我只想减少字典中键的值,这样当它达到 0 时,流星就会爆炸。

感谢您的快速回答(明白了吗?;)),希望你们能帮助我或指引我正确的方向!

标签: iosswiftsprite-kitskspritenodeuser-data

解决方案


推荐阅读