在touchesBegan事件中检测到触摸SKSpriteNode?
迄今为止,我的经验主要集中在将 GamepadController 与应用程序一起使用,而不是触摸激活的 iOS 应用程序。
以下是一些简短的代码片段:
注意:我试图纠正的错误已在评论中的第一个片段 =
touchesBegan
中注明 <== shows "horse"
是的,有一匹“马”,但它离我的
SKSpriteNode
文件中的“creditsInfo”.sks
不远=
请注意,这个“creditsInfo”
SKSpriteNode
是由我的addCreditsButton(..)
以编程方式生成的,并将放置在我的GameScene
的左上角附近。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let ourScene = GameScene(fileNamed: "GameScene") {
if let touch:UITouch = touches.first {
let location = touch.location(in: view)
let node:SKNode = ourScene.atPoint(location)
print("node.name = \(node.name!)") // <== shows "horse"
if (node.name == "creditsInfo") {
showCredits()
}
}
} // if let ourScene
} // touchesBegan
上面的
touchesBegan
函数是一个extension GameViewController
,根据文档,它是可以的,即,touchesBegan
除了是一个UIView
方法之外,还是一个UIViewController
方法。
在我的主要
showScene()
功能中,我有:
if let ourScene = GameScene(fileNamed: "GameScene") {
#if os(iOS)
addCreditsButton(toScene: ourScene)
#endif
}
与:
func addCreditsButton(toScene: SKScene) {
if thisSceneName == "GameScene" {
itsCreditsNode.name = "creditsInfo"
itsCreditsNode.anchorPoint = CGPoint(x: 0.5, y: 0.5)
itsCreditsNode.size = CGSize(width: 2*creditsCircleRadius,
height: 2*creditsCircleRadius)
itsCreditsNode.zPosition = 3
creditsCirclePosY = roomHeight/2 - creditsCircleRadius - creditsCircleOffsetY
creditsCirclePosX = -roomWidth/2 + creditsCircleRadius + creditsCircleOffsetX
itsCreditsNode.position = CGPoint(x: creditsCirclePosX,
y: creditsCirclePosY)
toScene.addChild(itsCreditsNode)
} // if thisSceneName
} // addCreditsButton
最后,我重复我在最上面所说的话:
我试图纠正的错误已在评论中的第一个片段 =
touchesBegan
中注明 <== shows "horse"
严格来说,这不是答案,但我在这里展示了上面最后一条评论所讨论的内容 - 但以更易读的格式。 希望这会产生一些急需的帮助:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let ourScene = GameScene(fileNamed: "GameScene") {
if let touch:UITouch = touches.first {
var position = CGPoint()
let location = touch.location(in: ourScene)
position.x = -roomWidth/2 + location.x
position.y = roomHeight/2 - location.y
let node:SKNode = ourScene.atPoint(position)
if (node.name == "creditsInfo") {
showCredits()
}
}
} // if let ourScene
} // touchesBegan
请注意,对于上面的touchesBegan
,
node.name
不是
itsCreditInfo
,而是room
,即紧接在我的下面的SKSpriteNode
。
请注意,我在本文顶部呈现的addCrreditsButton(...)
将不会改变