我正在尝试从Spritekit中的家庭场景更改为游戏场景。当我在模拟器中运行它时,没有过渡到GameScene。我还添加了一个打印命令,以查看是否已注册了播放按钮上的触摸,而没有注册。这是代码。谢谢!
import SpriteKit
class HomeScene: SKScene {
var playButton: SKSpriteNode?
var gameScene: SKScene!
override func didMove(to view: SKView) {
playButton = self.childNode(withName: "startButton") as? SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let pos = touch.location(in: self)
let node = self.atPoint(pos)
if node == playButton {
let transition = SKTransition.fade(withDuration: 1)
gameScene = SKScene(fileNamed: "GameScene")
gameScene.scaleMode = .aspectFit
self.view?.presentScene(gameScene, transition: transition)
print("touch")
}
}
}
}
答案 0 :(得分:1)
touches
方法内的touchesBegan(_: with:)
参数的类型为Set<UITouch>
,即一组触摸。如Apple Documentation for Sets中所述,当集合中各项的顺序无关紧要时,将使用一个集合。因此,您不能假定touches
中的第一项是集合中的第一触摸。知道这一点后,我建议将HomeScene.swift内部的代码重构为以下内容:
import SpriteKit
class HomeScene: SKScene {
private var playButton: SKSpriteNode?
override func sceneDidLoad() {
self.playButton = self.childNode(withName: "//starButton") as? SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
self.touchDown(atPoint: t.location(in: self))
}
}
func touchDown(atPoint pos: CGPoint) {
let nodes = self.nodes(at: pos)
if let button = playButton {
if nodes.contains(button) {
let gameScene = SKScene(fileNamed: "GameScene")
self.view?.presentScene(gameScene)
}
}
}
touchDown(atPoint:)
方法完成了所有繁重的工作,并且释放了touchesBegan(_: with:)
来监听触摸事件。调用childNode(withName:)
时要注意的另一件事:
/
,开始搜索从文件层次结构的根部开始的节点。//
,开始搜索从文件层次结构根目录开始的节点,然后递归向下搜索层次结构。*
充当字符通配符,并允许您搜索完全或部分未知的文件名。答案 1 :(得分:0)
我认为您应该使用节点的名称而不是节点本身来进行touchesBe ....的比较...
import SpriteKit
class HomeScene: SKScene {
var playButton: SKSpriteNode?
var gameScene: SKScene!
override func didMove(to view: SKView) {
playButton = self.childNode(withName: "startButton") as? SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let pos = touch.location(in: self)
let node = self.atPoint(pos)
if node.name == "startButton" {
let transition = SKTransition.fade(withDuration: 1)
gameScene = SKScene(fileNamed: "GameScene")
gameScene.scaleMode = .aspectFit
self.view?.presentScene(gameScene, transition: transition)
print("touch")
}
}
}
}
希望有帮助! :)