移动时如何访问 SKSpriteNode 子类的对象 (Swift)
How to access objects of SKSpriteNode subclass when moving them (Swift)
我对我的 class Card 的对象感到困惑,它是 SKSpriteNode 的子class。当用户移动这些对象时,我如何访问这些对象。到目前为止,我只能访问覆盖 touchesEnded 函数的 SKNode 对象。
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch : UITouch = touches.first as UITouch!
let touchLocation = touch.locationInNode(self)
touchedNode = self.nodeAtPoint(touchLocation)
touchedNode.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
touchedNode.zPosition = 0
}
我需要知道用户正在移动什么对象,但在这种情况下,当 touchedNode 是 SKNode class 的对象(不是我的 Card 对象 class)时,我无法弄清楚.
is
运算符正是您所需要的。
is
运算符比较两个操作数的类型。如果它们属于同一类型,或者一个是另一个的子class,则表达式的计算结果为真。
所以你可以这样检查:
if touchedNode is Card {
// do stuff
}
现在你可能想要做的是,如果 touchedNode
真的是一个 Card
,我想使用我在 Card
class 上定义的方法touchedNode
.
为此,您需要将 touchedObject
转换为 Card
:
let cardNode = touchedNode as! Card
然后您可以在 cardNode
!
上调用您的方法
我对我的 class Card 的对象感到困惑,它是 SKSpriteNode 的子class。当用户移动这些对象时,我如何访问这些对象。到目前为止,我只能访问覆盖 touchesEnded 函数的 SKNode 对象。
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch : UITouch = touches.first as UITouch!
let touchLocation = touch.locationInNode(self)
touchedNode = self.nodeAtPoint(touchLocation)
touchedNode.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
touchedNode.zPosition = 0
}
我需要知道用户正在移动什么对象,但在这种情况下,当 touchedNode 是 SKNode class 的对象(不是我的 Card 对象 class)时,我无法弄清楚.
is
运算符正是您所需要的。
is
运算符比较两个操作数的类型。如果它们属于同一类型,或者一个是另一个的子class,则表达式的计算结果为真。
所以你可以这样检查:
if touchedNode is Card {
// do stuff
}
现在你可能想要做的是,如果 touchedNode
真的是一个 Card
,我想使用我在 Card
class 上定义的方法touchedNode
.
为此,您需要将 touchedObject
转换为 Card
:
let cardNode = touchedNode as! Card
然后您可以在 cardNode
!