UserInteractionEnabled

UserInteractionEnabled

我到处都看过,但是什么也没用。以为我会问自己一个问题。我正在使用SpriteKit在iOS 9中创建一个小游戏。我的游戏将具有左右控制器按钮来移动玩家精灵。我为定向垫添加了SKSpriteNodes,如下所示

在主要场景的顶部,我输入:

private var leftDirectionalPad = SKSpriteNode(imageNamed: "left")
private var rightDirectionalPad = SKSpriteNode(imageNamed: "right")

然后我运行一个名为prepareDirectionalPads的方法
    func prepareDirectionalPads() {

    // left

    self.leftDirectionalPad.position.x = self.size.width * directionalPadLeftXPositionMultiplier
    self.leftDirectionalPad.position.y = self.size.height*directionalPadYPosition
    self.leftDirectionalPad.size.width = self.leftDirectionalPad.size.width/directionalPadSizeReductionMultiple
    self.leftDirectionalPad.size.height = self.leftDirectionalPad.size.height/directionalPadSizeReductionMultiple

    self.leftDirectionalPad.name = "leftDirectionalPad"
    self.leftDirectionalPad.alpha = directionalPadAlphaValue
    self.leftDirectionalPad.zPosition = 1
    self.addChild(leftDirectionalPad)
    self.leftDirectionalPad.userInteractionEnabled = true

    // right

    self.rightDirectionalPad.position.x = self.leftDirectionalPad.position.x*directionalPadSpacingMultiple
    self.rightDirectionalPad.position.y = self.size.height*directionalPadYPosition
    self.rightDirectionalPad.size.width = self.rightDirectionalPad.size.width/directionalPadSizeReductionMultiple
    self.rightDirectionalPad.size.height = self.rightDirectionalPad.size.height/directionalPadSizeReductionMultiple

    self.rightDirectionalPad.name = "rightDirectionalPad"
    self.rightDirectionalPad.alpha = directionalPadAlphaValue
    self.rightDirectionalPad.zPosition = 1
    self.addChild(rightDirectionalPad)
    self.rightDirectionalPad.userInteractionEnabled = true

}

我清楚地将每个SKSpriteNode的userInteractionEnabled设置为true。然后,我开始接触……
override func touchesBegan(let touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */
        var touch = touches.first! as UITouch
        var location = touch.locationInView(self.view)
        var node = nodeAtPoint(location)

        print("Touched")
 }

注意:我也尝试了var location = touch.locationInNode(self),但这也不起作用。

然后,我运行该应用程序(在我的xCode Simulator或iPhone 6上)。如果我触摸SKNode,则什么也不会发生。什么都没有打印到控制台。但是,如果我触摸屏幕上的任何其他位置,则会“触摸”到屏幕上。

我究竟做错了什么?我想检测垫子上的触摸,以便相应地移动播放器精灵。我可能忘了做这件事确实很愚蠢。感谢您的时间和耐心等待。非常感激。

最佳答案

弄清楚了。因此,显然self.leftDirectionalPad.userInteractionEnabled = true不起作用。它必须是self.leftDirectionalPad.userInteractionEnabled = false,这非常违反直觉。我不明白,但现在可以使用。当用户触摸SKSpriteNode时,touchesBegan做出响应。

    let touch = touches.first! as UITouch
    let location = touch.locationInNode(self)
    let node = nodeAtPoint(location)

    if(node.name == leftDirectionalPad.name)
    {
        print("left")
    }
    else if (node.name == rightDirectionalPad.name)
    {
         print("right")
    }

09-06 11:39