TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: How can I make background of an SKScene transparent so I can layer in a ZStack?

Forums > SwiftUI

@Mary  

I'm trying to make a game using SwiftUI and SpriteKit. And I want to be able to layout the game in a ZStack with the game layered over the background image. In order to do that, I need to make the background of the SKScene transparent. But when I do that, the nodes that I add to the SKScene no longer show up.

Here's the coding that I'm using:

import SwiftUI
import SpriteKit
import GameplayKit

class GameScene: SKScene {

  override func didMove(to view: SKView) {

    view.allowsTransparency = true
    self.backgroundColor = .clear
    view.alpha = 0.0
    view.isOpaque = true
    view.backgroundColor = SKColor.clear.withAlphaComponent(0.0)

    if let particles = SKEmitterNode(fileNamed: "Mud") {
      particles.position.x = 512
      addChild(particles)
    }

  }

}

struct ContentView: View {

  var scene: SKScene {

    let scene = GameScene()
    scene.size = CGSize(width: 300, height: 400)
    scene.scaleMode = .fill

    return scene
  }

  var body: some View {
    ZStack {
      Image("road")
        .resizable()
        .aspectRatio(contentMode: /*@START_MENU_TOKEN@*/.fill/*@END_MENU_TOKEN@*/)
        .ignoresSafeArea()
      SpriteView(scene: scene)
        .ignoresSafeArea()
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
    }
  }
}

The background of the SKScene is, in fact, transparent and I can see the image layered underneath it in the ZStack. But, everything else in the scene is also transparent so that I can't see the emitter effect at all.

How can I make just the background of the SKScene transparent?

3      

All you need is to set the scene background to .clear, and to pass options as a parameter to the SpriteView for transparency. So for your case, it would be SpriteView(scene: scene, options: [.allowsTransparency]). All the SKView modifications can be removed.

5      

@Mary  

@adrianensan! Thank you so much! That works and it's exactly what I was looking for. Thank you again!

4      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.