小编典典

如何检测是否已触摸SKSpriteNode

swift

我试图检测我的sprite节点是否已被触摸并且我不知道从哪里开始。

let Pineapple = SKSpriteNode(imageNamed: "Pineappleimg")
Pineapple.userInteractionEnabled = true
Pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame));
self.addChild(Pineapple)

阅读 313

收藏
2020-07-07

共1个答案

小编典典

首先将的name属性设置SKSpriteNode为字符串。

pineapple.name = "pineapple"
pineapple.userInteractionEnabled = false

然后在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)
2020-07-07