无法将 child 添加到 GameScene,只能添加到 SKSpriteNode

Can't add a child to GameScene, only to a SKSpriteNode

我正在尝试在按下按钮时从 class(行星)创建一个 SKSpriteNode 到我的 GameScene。我的问题是边框没有出现在屏幕上。

class Planets: SKSpriteNode, EventListenerNode, InteractiveNode {

var gameScene: GameScene!

func didMoveToScene(){
    isUserInteractionEnabled = true
    gameScene = (SKScene(fileNamed: "GameScene") as! GameScene)
}

func interact() {
    print("hi \(self.name ?? "Planet X")")
    let border = SKSpriteNode(color: SKColor.gray, size: CGSize(width: 200, height: 200))
    border.name = "border"
    border.zPosition = 100
    border.position = CGPoint(x: gameScene.frame.size.width/2, y: gameScene.frame.size.height/2)
    gameScene.addChild(border)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    interact()
}

}

但是,如果我使用 self.addChild,(意思是行星 class)它会起作用,所以如果我将边框添加到 SKSpriteNode,它会起作用,但我不想要那样,因为大小不同,位置也不同。我只想将它添加到我的 GameScene 中。 提前致谢!

我认为这里的问题是 Planets class 正在用这里的这一行创建它自己的 GameScene 副本:

gameScene = (SKScene(fileNamed: "GameScene") as! GameScene)

该副本从未出现,因此它永远不可见,添加到它的边框也不可见。

如果 PlanetsGameScene 的子节点,那么当您像这样添加边框时,我会尝试引用 Planets 节点的父节点:

func interact() {
    print("hi \(self.name ?? "Planet X")")

    guard let gameScene = self.parent as? GameScene else {
        print("Error: could not get the parent scene")
        return
    }

    let border = SKSpriteNode(color: SKColor.gray, size: CGSize(width: 200, height: 200))
    border.name = "border"
    border.zPosition = 100
    border.position = CGPoint(x: gameScene.frame.size.width/2, y: gameScene.frame.size.height/2)
    gameScene.addChild(border)
}