How to build SpriteKit game using SwiftUI?

Hey Developers 👋,

What would be the best possible way to use SwiftUI as the UI for SpriteKit game? Enabling all the powerful features of SwiftUI to be used in a SpriteKit project?

Continue having a great WWDC,

Danny

I am using SwiftUi and Spritekit for my level editor (the game don't use SwiftUi) That's an example like my project (I removed most of the content because my scene has many code)

I hope it will help you

You create you Spritkit Scene file

import Foundation
import SpriteKit
import SwiftUI

class SceneTileMap: SKScene {

    var tileMap : SKTileMapNode!
    var tileSet : SKTileSet!
    ...

    override func didMove(to view: SKView) {
         ... 
     }
     override func mouseDown(with event: NSEvent) {
         ...
     }
}

And in the same file you add the code for create the swiftUI view :

struct MapView: View {
    @EnvironmentObject var paramConstructeur: ParamètresConstructeur

    var scene: SceneTileMap {
        let scene = SceneTileMap()
        scene.size = CGSize(width: 1000, height: 800)
        scene.scaleMode = .fill
        scene.paramConstructeur = paramConstructeur
        return scene
    }

    func updateparams() {
        scene.paramConstructeur = paramConstructeur
    }

    var body: some View {
        SpriteView(scene: scene)
            .padding(.all)
            .frame(width: 1000, height: 800)
            .ignoresSafeArea()
    }
}

Presumably you'd use UIViewRepresentable to wrap the SKView. The code to deal with the nodes would depend on the details of your application.

Accepted Answer

I am using SwiftUi and Spritekit for my level editor (the game don't use SwiftUi) That's an example like my project (I removed most of the content because my scene has many code)

I hope it will help you

You create you Spritkit Scene file

import Foundation
import SpriteKit
import SwiftUI

class SceneTileMap: SKScene {

    var tileMap : SKTileMapNode!
    var tileSet : SKTileSet!
    ...

    override func didMove(to view: SKView) {
         ... 
     }
     override func mouseDown(with event: NSEvent) {
         ...
     }
}

And in the same file you add the code for create the swiftUI view :

struct MapView: View {
    @EnvironmentObject var paramConstructeur: ParamètresConstructeur

    var scene: SceneTileMap {
        let scene = SceneTileMap()
        scene.size = CGSize(width: 1000, height: 800)
        scene.scaleMode = .fill
        scene.paramConstructeur = paramConstructeur
        return scene
    }

    func updateparams() {
        scene.paramConstructeur = paramConstructeur
    }

    var body: some View {
        SpriteView(scene: scene)
            .padding(.all)
            .frame(width: 1000, height: 800)
            .ignoresSafeArea()
    }
}

Thank you! This actually helps a lot! Much appreciation, will see how we can incorporate this into our workflow.

How to build SpriteKit game using SwiftUI?
 
 
Q