SKLightNode's shadow doesn't hide sprites

190 views Asked by At

I'm currently working with a SKLightNode and I have some sprites on the screen. I want those sprites to cast a shadow depending on the light's position, but I want the sprites lit directly by the light to be shown and the sprites behind another sprites to be hidden.

I have this code :

let light = SKLightNode()

override func didMove(to view: SKView)
{        
    light.categoryBitMask = 1
    light.falloff = 1.0
    light.shadowColor = SKColor.black
    light.zPosition = 2
    addChild(light) // I add the light

    for _ in 0...10
    {
        let object = SKSpriteNode(imageNamed: "stone")
        object.position = CGPoint(x: CGFloat.random(min: playableRect.minX, max: playableRect.maxX), y: CGFloat.random(min: playableRect.minY, max: playableRect.maxY))
        object.shadowCastBitMask = 1
        object.zPosition = 2
        addChild(object) // I add 10 wall sprites
    }
}

This results in this : enter image description here

As you can see, the problem is that the sprites in the shadow aren't hidden.

When I change the walls' zPosition to 1 (lower than the light's zPosition), I have this :

enter image description here

Here everything is hidden, still not good.

I read in an old stackoverflow question from 2015 that SpriteKit does not support this kind of situation. Is it still the case ? Anyway, is there a workaround ?

1

There are 1 answers

0
Marcin Żmigrodzki On

I had the same problem and found solution.

  1. add shadowedBitMask responding to the sprite
  2. make sure that light is higher in zposition than sprite that should be covered by shadow

Here is an example:

sprite.shadowedBitMask = 0b0001
sprite.zPosition = 1
light.zPosition = 2
light.categoryBitMask = 0b0001