Search code examples
swiftsprite-kitswift-playground

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


I tried copying the template code from a SpriteKit project into a playground, but all I get is a grey screen when I present the Scene. Do I need to create an SKScene and if so how do I assign it to the scene class that I am using.

The following is my code to create and present the scene:

 @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


}

And this is my SKScene class, which has a filename of 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) {
}
}

Solution

  • Assuming you have dragged and dropped your MainScreenBackground.png image into you Assets.xcassets folder, you can use the code below to add the image to your scene as a SKSpriteNode.

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