gpt4 book ai didi

swift - 错误 : Could not cast value of type 'Ninjumper.GameScene' to 'SKSpriteNode' when trying to transition

转载 作者:行者123 更新时间:2023-11-28 07:20:59 24 4
gpt4 key购买 nike

(我仍在快速学习,请耐心等待)。我目前正在尝试编写一个名为“Ninjumper”的简单 2D 平台游戏。我在我的 GameScene 中设置了实际的平台游戏,我目前正在创建一个带有“播放”按钮的主菜单,该按钮会将您带到 GameScene。我的 MenuScene 上只有一个颜色 Sprite (带有纹理“播放按钮”),我以编程方式将其制作成一个按钮。但是,当单击此按钮时,我的程序崩溃并出现标题中显示的错误。

这是我的 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”。我应该如何解决这个问题? (或者如果你有其他方法可以制作按钮切换场景,请告诉我)

最佳答案

试试这个。将 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)
}
}

祝你好运!我会关注这个问题,所以如果你遇到同样的问题请告诉我:)

关于swift - 错误 : Could not cast value of type 'Ninjumper.GameScene' to 'SKSpriteNode' when trying to transition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085205/

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