theloneswiftman
theloneswiftman

Reputation: 188

SKNode now shown from another class

I've two classes in separate files.

In the "main" file, where my scene is, I'm calling this function:

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

    for touch in touches {
        character().spawnCharacter()
    }
}

So, in my second file, character.swift I've this code:

import SpriteKit

public func spawnCharacter() -> SKSpriteNode{
    let charNode = SKSpriteNode(imageNamed: "Hero")
    charNode.name = "Hero"
    charNode.postion = CGPointZero
    charNode.zPosition = 3
    addChild(charNode)
    print("Node added")
    return charNode
}

So, the print line is printed, but the node is never added.

I've been over my code a couple of times, but I can't crack it.

Any clues?

Upvotes: 0

Views: 33

Answers (1)

0x416e746f6e
0x416e746f6e

Reputation: 10136

I am not entirely sure how your main file is organised, but I think the problem is here:

for touch in touches {
    character().spawnCharacter() // <- SKSpriteNode is created but not added
}

You create sprite-node in spawnCharacter() but you do not use the returned object.

Potential fix would be:

for touch in touches {
    let character = character().spawnCharacter()
    scene.addChild(character)
}

Upvotes: 1

Related Questions