Search code examples
swiftsprite-kitskspritenodeskscene

How to change the alpha value of spriteNode?


I am changing the alpha value of spriteNode like this,

if (firstBody.node?.name)! == "Player" && secondBody.node?.name == "Alpha 1" {

        var item: SKSpriteNode?
        item = SKSpriteNode(imageNamed: "BG")
        item!.alpha = 0.1

        score += 1
        scoreLabel?.text = String(score)
}

This is mentioned in the documentation (use node.alpha = value), but I am not sure why it isn't working.


Solution

  • you can fade the alpha by using a Action, I have left an example below.

    class GameScene: SKScene {  
      var player: SKSpriteNode!  
    
      override func didMove(to view: SKView) {
            player = SKSpriteNode(color: .purple, size: CGSize(width: 100, height: 100))      
            player.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
            self.addChild(player)            
        }
    
        func fadePlayer() {    
            let fadeAlpha = SKAction.fadeAlpha(to: 0.1, duration: 1.0)
            self.run(fadeAlpha)
        }
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            fadePlayer()
        }
    
    }
    

    When a touch begins the SpriteNode will fade out to the alpha value you insert, it will fade out gradually during a time you insert in the duration also, This action fades the SpriteNode's alpha to 0.1 gradually over 1 second.