Home > Back-end >  Display particle emitter in SwiftUI View
Display particle emitter in SwiftUI View

Time:09-25

Trying to use SKScene to display a particle emitter spritekit file in a View.

Current code

struct ContentView: View {
 
    var scene: SKScene {
            let scene = SKScene(fileNamed: "magicSparkles")!
            scene.size = CGSize(width: 400, height: 400)
            scene.scaleMode = .fill
            return scene
        }
    
    var body: some View {
        VStack {
            Text("Hello, World!")
                .padding()
            SpriteView(scene: scene)
                       .frame(width: 400, height: 400)
                       .edgesIgnoringSafeArea(.all)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Whenever I try to do this the simulator throws an error.

Moodie2 WatchKit Extension crashed due to an uncaught exception NSInvalidArgumentException. Reason: -[SKEmitterNode setScaleMode:]: unrecognized selector sent to instance 0x600003e981c0.

CodePudding user response:

Try instead of using SKScene(fileNamed: "magicSparkles"), replace the SKScene with SKEmitterNode. Not sure if the rest of the code will run correctly though

CodePudding user response:

I have a partial answer to this question, although it has an issue that I have been unable to solve on the watch. I have used Spritekit with SwiftUI on an iOS device, but never on watchOS. The first thing I learned is that func didMove() does not exist on watchOS, so you have to use func sceneDidLoad() to implement things. The following code will put an emitter on the watch:

import SwiftUI
import SpriteKit

struct ContentView: View {
    var scene = EmitterScene()

    var body: some View {
        GeometryReader { geometry in
       SpriteView(scene: scene)

         
        }
    }
}

class EmitterScene: SKScene {
    
    override func sceneDidLoad() {
        if let emitter = SKEmitterNode(fileNamed: "magicSparkles"){
            emitter.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
            emitter.zPosition = -1
            addChild(emitter)
        }
    }
}

The problem I am having with it is that the emitter particles do not appear correctly. They are overly large and you have to futz with the emitter to make it dense enough that they regularly show, but they seem to be scaled up to almost the same size as the watch face itself. I have no idea how to resolve that.

  • Related