如何检测是否已触摸

如何检测是否已触摸

本文介绍了如何检测是否已触摸 SKSpriteNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测我的精灵节点是否已被触摸,但我不知道从哪里开始.

I am trying to detect if my sprite node has been touched and I have no idea where to start.

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

推荐答案

首先将SKSpriteNodename属性设置为字符串.

First set the name property of the SKSpriteNode to a string.

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

然后在Scene中的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.

This is one way to do it.
You can also subclass SKSpriteNode and override the touchesBegan inside it.

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)

这篇关于如何检测是否已触摸 SKSpriteNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:47