Luiz Luiz - 1 year ago 37
Swift Question

Fade in when hidden

I'm trying to fade in an object into my game when I first touch the screen, but I think that because it was hidden before (when game was launched), it won't fade in, but only show without any animation.

Do you have any suggestions?

This is an example code:

import SpriteKit

class GameScene: SKScene {

var myLabel = SKLabelNode()
var gameStarted = Bool()

func setupMyLabel(){
myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!"
myLabel.fontSize = 35
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))

override func didMoveToView(view: SKView) {
/* Setup your scene here */

myLabel.hidden = true

gameStarted = false

func startGame(){
myLabel.hidden = false

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */

if gameStarted == false{

gameStarted = true

//do nothing


According to Apple's documentation on fadeInWithDuration it states that:

When the action executes, the node’s alpha property animates from its current value to 1.0.

So you're right in thinking it's because your node is hidden when it starts. =)

One possible solution would be to instead of setting the node's hidden property to true, instead set it's alpha value to 0. Or you could even create your own method to perform that includes the runAction method that would set the alpha to 0, un-hide the node, and then call SKAction.fadeInWithDuration similar to something below (please forgive any syntax errors, this is free-hand pseudo code)...

self.fadeIn(self.myLabel, duration: 2.0)


func fadeIn() {
    self.myLabel.alpha = 0.0
    self.myLabel.hidden = false