如何在 Swift Playgrounds 中使用带有纹理的 SKNode 设置 SKScene?

How to set up an SKScene with an SKNode with a texture in Swift Playgrounds?

我尝试将模板代码从 SpriteKit 项目复制到 playground 中,但是当我呈现场景时,我得到的只是一个灰色屏幕。我需要创建一个 SKScene 吗?如果需要,我如何将它分配给我正在使用的场景 class。

以下是我创建和呈现场景的代码:

 @objc func goToGameScene(){

    print("GameView Loaded")

 sceneView = SKView(frame: CGRect(x: 0, y: 0, width: 666, height: 500))



sceneView.backgroundColor = UIColor.black

PlaygroundPage.current.liveView = sceneView

if let view = self.sceneView as SKView? {
    // Load the SKScene from 'GameScene.sks'
    if let scene = SKScene(fileNamed: "GameScene") {
        // Set the scale mode to scale to fit the window
        scene.scaleMode = .aspectFill

        // Present the scene
        view.presentScene(scene)
    }

    view.ignoresSiblingOrder = true


}

这是我的 SKScene class,文件名为 GameScene.swift。

import Foundation
import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {
var bg = SKSpriteNode()
func didBegin(_ contact: SKPhysicsContact) {
}
override func didMove(to view: SKView) {
    self.physicsWorld.contactDelegate = self
    let bgTexture = SKTexture(image: UIImage(named: "MainScreenBackground.png")!)
    let moveBGAnimation = SKAction.move(by: CGVector(dx:-bgTexture.size().width, dy:0), duration: 11)
    let shiftBackground = SKAction.move(by: CGVector(dx: bgTexture.size().width, dy:0), duration: 0)
    let repeatAnimationBg = SKAction.repeatForever(SKAction.sequence([moveBGAnimation, shiftBackground]))
    var q = 0
    while(q < 3){
        bg = SKSpriteNode(texture: bgTexture)
        bg.position = CGPoint(x:  bgTexture.size().width * CGFloat(q), y: self.frame.midY)
        bg.size.height = self.frame.height
        bg.run(repeatAnimationBg)
        self.addChild(bg)
        q+=1
        bg.zPosition = -1
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
}
}

假设您已将 MainScreenBackground.png 图像拖放到 Assets.xcassets 文件夹中,您可以使用下面的代码将图像作为 SKSpriteNode 添加到场景中。

override func didMove(to view: SKView) {
    self.physicsWorld.contactDelegate = self
    let bgTexture = SKSpriteNode(imageNamed: "MainScreenBackground")
    self.addChild(bgTexture)
    ...