Sprite Kit Button 触摸位置错误 | Swift

Sprite Kit Button touch location error | Swift

我正在尝试制作一个 SKLabelNode 按钮。当它被按下时,它应该改变场景,但是声明位置的那一行有问题。

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)

    let location = touches.locationInNode(self)
    let touchedNode = self.nodeAtPoint(location)

    if touchedNode.name == "startGameButton" {
        let transition = SKTransition.revealWithDirection(SKTransitionDirection.Down, duration: 1.0)

        let scene = GameScene(size: self.scene.size)
        scene.scaleMode = SKSceneScaleMode.AspectFill

        self.scene.view.presentScene(scene, transition: transition)
    }
}

错误在这里就行了。

let location = touches.locationInNode(self)

它显示为

'Set< NSObject>' does not have a member named 'locationInNode'

我不确定如何修复它。我看过很多可用的按钮模板,但我的总是出错。

问题正是错误所述 - Set<NSObject> 没有名为 locationInNode 的方法。您需要做的是从 Set; 中检索一个对象;检查它是一个 UITouch 对象;如果是,您可以使用它来获取触摸位置。尝试:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let location = (touches.first as? UITouch)?.locationInNode(self) {
        // ...
    }
}

或者

if let touch = touches.first as? UITouch {
    let location = touch.locationInNode(self)
    // ...
}

要修复它,这是默认修复,它只是枚举所有的触摸。

for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        node = self.nodeAtPoint(location)
        //do something
}