(我还在学习swift,请耐心听我说)。我目前正在尝试编写一个简单的2D平台游戏,叫做“忍者”。我已经在我的GameScene中设置了实际的platformer游戏,目前我正在创建一个带有“播放”按钮的主菜单,它会带你进入GameScene。我的MenuScene上只有一个彩色雪碧图(带有纹理"playbutton"),我已经通过编程把它做成了一个按钮。但是,当单击此按钮时,我的程序崩溃,并显示标题中显示的错误。
下面是我的MenuScene中的代码:
//
// MenuScene.swift
// Ninjumper
import SpriteKit
class MenuScene: SKScene {
var playButton = SKSpriteNode(texture: SKTexture(imageNamed: "playbutton"))
override func didMove(to view: SKView) {
addPlayButton()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let touchedNode = atPoint(location)
if touchedNode.name == "playButton" {
// Call the function here.
let scene = GameScene(fileNamed: "GameScene")!
let transition = SKTransition.moveIn(with: .right, duration: 1)
self.view?.presentScene(scene, transition: transition)
}
}
}
func addPlayButton() {
playButton.position = CGPoint(x: 0, y: -156)
playButton.name = "playButton"
playButton.size = CGSize(width: 280.0, height: 100.0)
playButton.isHidden = false
addChild(playButton)
}
}我想让它变成这样,当你轻敲按钮时,场景从MenuScene切换到GameScene。但是,我当前使用的代码导致了错误:无法将'Ninjumper.GameScene‘类型的值转换为'SKSpriteNode’。我该如何解决这个问题呢?(或者如果你有其他方法来切换场景,请告诉我)
发布于 2019-09-27 10:10:59
尝尝这个。将touchesBegan的内容替换为以下内容:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}现在创建一个名为touchDown的新函数
func touchDown(atPoint pos : CGPoint) { /* ... */ }在我们的新函数中:
if playButton.contains(pos) {
if let scene = GameScene(fileNamed: "GameScene") {
scene.scaleMode = .aspectFit
let t = SKTransition.moveIn(with: .right, duration: 1)
self.view?.presentScene(scene, transition: t)
}
}祝你好运!我会关注这个问题,如果你遇到同样的问题,请告诉我:)
https://stackoverflow.com/questions/58085205
复制相似问题