SKSpriteNode UserInteractionEnabled不起作用

时间:2015-11-22 01:13:15

标签: ios swift ios9 skspritenode

我到处都看,但没有任何作用。以为我会问自己这个问题。我正在使用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模拟器或iPhone 6上)。如果我触摸SKNodes,没有任何反应。控制台上没有任何内容。但是,如果我触摸屏幕上的任何其他位置,我会“触摸”打印到屏幕上。

我做错了什么?我想检测打击垫上的触摸,这样我就可以相应地移动玩家精灵。这可能是我忘记做的非常愚蠢的事情。感谢您的时间和耐心。非常感激。

1 个答案:

答案 0 :(得分:2)

想出来。显然self.leftDirectionalPad.userInteractionEnabled = true不起作用。它必须是self.leftDirectionalPad.userInteractionEnabled = false,这非常违反直觉。我不明白,但它现在有效。 touchesBegan在用户触摸SKSpriteNode时响应。

    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")
    }