ios - 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 时,流星就会爆炸。
感谢您的快速回答(明白了吗?;)),希望你们能帮助我或指引我正确的方向!
解决方案
推荐阅读
- twilio - Twilio Conversations SDK - 设置上次读取索引不起作用
- c# - 如何从另一个窗体 c# 隐藏 DataGridView 中的列
- javascript - 理解 Javascript 对象和未定义
- c# - 我收到异常“发生约束冲突。\r\n”
- automapper - Automapper 走下关系
- node.js - 我收到错误“位置的 JSON 中出现意外的令牌...”
- go - 如何将 Go 可执行文件与 Windows 上的 Go 编译库静态链接?
- python - 在字节或字符串python中用单个反斜杠替换双反斜杠
- c# - 如何暂时解除 AWS SQS 队列与触发 Lambda 的关联,以便将消息暂时累积到队列上?
- linux - 在正在运行的容器中找不到来自 Docker 映像的依赖项