我到处都找过了,但没有任何效果。我想我会自己问这个问题。我正在使用 SpriteKit 在 iOS 9 中创建一个小游戏。我的游戏将有左右 Controller 按钮来移动玩家 Sprite 。我为方向垫添加 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 上)。如果我触摸 SKNodes,什么也不会发生。控制台上没有打印任何内容。但是,如果我触摸屏幕上的其他任何位置,我就会将“触摸”打印到屏幕上。
我做错了什么?我想检测打击垫上的触摸,以便我可以相应地移动玩家 Sprite 。这可能是我忘记做的一件非常愚蠢的事情。感谢您的时间和耐心。非常感激。
最佳答案
想通了。所以显然 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")
}
关于ios - SKSpriteNode UserInteractionEnabled 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33850541/