我试图检测我的sprite节点是否已被触摸并且我不知道从哪里开始。
let Pineapple = SKSpriteNode(imageNamed: "Pineappleimg") Pineapple.userInteractionEnabled = true Pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame)); self.addChild(Pineapple)
首先将的name属性设置SKSpriteNode为字符串。
name
SKSpriteNode
pineapple.name = "pineapple" pineapple.userInteractionEnabled = false
然后在touchesBegan功能上Scene
touchesBegan
Scene
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch:UITouch = touches.anyObject()! as UITouch let positionInScene = touch.locationInNode(self) let touchedNode = self.nodeAtPoint(positionInScene) if let name = touchedNode.name { if name == "pineapple" { print("Touched") } } }
这是一种方法。 您也可以继承SKSpriteNode并覆盖其中的touchesBegan内部。
class TouchableSpriteNode : SKSpriteNode { override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { print("touched") } }
然后做
let pineapple = TouchableSpriteNode(imageNamed: "Pineappleimg") pineapple.userInteractionEnabled = true pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame)); self.addChild(pineapple)