我试图为一个SKSpriteNode创建一个自定义操作块,我有以下代码:
let sprite = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))
sprite.position = CGPoint(x: 320, y: 240)
self.addChild(sprite)
let animation = SKAction.customAction(withDuration: 0, actionBlock: {
(node, elapsedTime) in
var initialValue : CGFloat?
initialValue = node[keyPath: \SKSpriteNode.position.x] //Extraneous argument label 'keyPath:' in subscript
node[keyPath: \SKSpriteNode.position.x] = 10 //Ambiguous reference to member 'subscript'
})
sprite.run(animation)我得到了两个错误,第一个错误是编译器认为我有一个无关的'keyPath‘参数,情况并非如此,因为如果我按照它的建议删除它,我就会得到这个错误:
无法将“ReferenceWritableKeyPath”类型的值转换为预期的参数类型“String”
我得到的第二个错误是:
对成员“下标”的模糊引用
我不太清楚为什么会有这些错误,我也不知道这些错误到底意味着什么。如果有人能向我解释并提出解决方案,那就太好了。提前谢谢。
发布于 2017-08-27 22:56:33
keyPath无法工作,因为node有SKNode类型,而没有SKSpriteNode类型。可以使用条件强制转换来确定节点是SKSpriteNode。
let animation = SKAction.customAction(withDuration: 0, actionBlock: {
(node, elapsedTime) in
var initialValue : CGFloat?
if let spritenode = node as? SKSpriteNode {
initialValue = spritenode[keyPath: \SKSpriteNode.position.x]
spritenode[keyPath: \SKSpriteNode.position.x] = 10
}
})https://stackoverflow.com/questions/45909769
复制相似问题