首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误:尝试转换时,无法将'Ninjumper.GameScene‘类型的值强制转换为'SKSpriteNode’

错误:尝试转换时,无法将'Ninjumper.GameScene‘类型的值强制转换为'SKSpriteNode’
EN

Stack Overflow用户
提问于 2019-09-25 01:11:04
回答 1查看 35关注 0票数 1

(我还在学习swift,请耐心听我说)。我目前正在尝试编写一个简单的2D平台游戏,叫做“忍者”。我已经在我的GameScene中设置了实际的platformer游戏,目前我正在创建一个带有“播放”按钮的主菜单,它会带你进入GameScene。我的MenuScene上只有一个彩色雪碧图(带有纹理"playbutton"),我已经通过编程把它做成了一个按钮。但是,当单击此按钮时,我的程序崩溃,并显示标题中显示的错误。

下面是我的MenuScene中的代码:

代码语言:javascript
复制
//
//  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’。我该如何解决这个问题呢?(或者如果你有其他方法来切换场景,请告诉我)

EN

回答 1

Stack Overflow用户

发布于 2019-09-27 10:10:59

尝尝这个。将touchesBegan的内容替换为以下内容:

代码语言:javascript
复制
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}

现在创建一个名为touchDown的新函数

代码语言:javascript
复制
func touchDown(atPoint pos : CGPoint) { /* ... */ }

在我们的新函数中:

代码语言:javascript
复制
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)
  }
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58085205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档