2017-08-27 30 views
0

我试图为SKSpriteNode创建一个自定义操作块,我有以下代码:智能KeyPaths不能正常工作

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”,这是不是这样,一个外来的说法,因为如果我喜欢它建议删除它,我得到这个错误:

Cannot convert value of type 'ReferenceWritableKeyPath' to expected argument type 'String'

第二个错误我得到的是:

Ambiguous reference to member 'subscript'

我不完全确定为什么我会得到所有这些错误,而且我不确定错误是什么意思。如果有人能够向我解释并提出解决方案,那就太好了。提前致谢。

回答

1

keyPath不工作,因为nodeSKNode而不是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 
    } 
})