gpt4 book ai didi

swift - 在 Spritekit 中改变场景,检测按钮上的触摸

转载 作者:行者123 更新时间:2023-11-28 14:31:12 25 4
gpt4 key购买 nike

我正尝试在 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")
}

}
}

最佳答案

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:)还有一点要注意:

  • 正在添加 /在文件名开始搜索从文件层次结构的根开始的节点之前。
  • 正在添加 //在文件名开始搜索从文件层次结构的根开始的节点之前,然后向下递归层次结构。
  • 正在添加 *在文件名之前用作字符通配符,并允许您搜索完全或部分未知的文件名。

关于swift - 在 Spritekit 中改变场景,检测按钮上的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com