因此,对于一个学校项目,我的任务是制作一款 2D 游戏。游戏很好,但我正在为如何制作后退按钮(在页面中间)而苦苦挣扎,所以想知道是否有特定的代码可以使它正常工作。我正在使用 spriteKit,所以我试图在点击一个彩色 Sprite 后返回到之前的场景。
如果这是一个愚蠢的问题,我深表歉意,但我对 Swift 有点陌生。
亲切的问候, 詹姆斯
最佳答案
这是一个示例,说明如何使用彩色 sprite 创建按钮。它展示了如何设置按钮来接收触摸事件,以及如何使用这些触摸事件在场景之间导航。
在此示例中,您可以向前导航到新场景并向后导航到以前的场景。
import SpriteKit
class Button: SKSpriteNode {
var tapped: (() -> Void)?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
tapped?()
}
}
class GameScene: SKScene {
var parentScene: SKScene?
var sceneCount = 1
override func didMove(to view: SKView) {
if parentScene != nil {
let backButton = addButton(color: .red, position: CGPoint(x: -200, y: 0))
backButton.tapped = {
if let previousScene = self.parentScene {
view.presentScene(previousScene)
}
}
}
let nextButton = addButton(color: .blue, position: CGPoint(x: 200, y: 0))
nextButton.tapped = {
if let nextScene = SKScene(fileNamed: "GameScene") as? GameScene {
nextScene.scaleMode = self.scaleMode
nextScene.parentScene = self
nextScene.sceneCount = self.sceneCount + 1
view.presentScene(nextScene)
}
}
let label = SKLabelNode(text: "Scene \(sceneCount)")
addChild(label)
}
func addButton(color: SKColor = .white, position: CGPoint = .zero) -> Button {
let button = Button(color: color, size: CGSize(width: 200, height: 200))
button.position = position
button.isUserInteractionEnabled = true
addChild(button)
return button
}
}
关于ios - 在swift中点击一个颜色 Sprite 后如何返回到之前的场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44079350/