swift – 如何检测SKSpriteNode是否被触摸

前端之家收集整理的这篇文章主要介绍了swift – 如何检测SKSpriteNode是否被触摸前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图检测我的精灵节点是否被触动,我不知道从哪里开始。
let Pineapple = SKSpriteNode(imageNamed: "Pineappleimg")
Pineapple.userInteractionEnabled = true
Pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200,y: CGRectGetMidY(self.frame));
self.addChild(Pineapple)
首先将SKSpriteNode的name属性设置为字符串。
pineapple.name = "pineapple"
pineapple.userInteractionEnabled = false

然后在场景中的touchesBegan功能

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)

猜你在找的Swift相关文章