squarehippo10 squarehippo10 - 4 months ago 6
Swift Question

Creating and Using Classes

If I create an instance of the class below and call the spawn function from my controller, the sprite will appear but I won't be able to change any of its properties.

class Hero: SKSpriteNode
var hero = SKSpriteNode(imageNamed: "hero3")

func spawn(parentNode: SKNode, position: CGPoint, size: CGSize = CGSize(width: 50, height: 50))
hero.size = size
hero.position = position
hero.physicsBody = SKPhysicsBody(circleOfRadius: 25)
hero.physicsBody?.allowsRotation = false
hero.zPosition = 10

If I get rid of the hero property and change everything to self, it works fine.

class Hero: SKSpriteNode
func spawn(parentNode: SKNode, position: CGPoint, size:CGSize = CGSize(width: 50, height: 50))
self.size = size
self.position = position
self.texture = SKTexture(imageNamed: "hero3")
self.physicsBody = SKPhysicsBody(circleOfRadius: 25)
self.physicsBody?.allowsRotation = false
self.zPosition = 10

I'm sure this is swift 101, but can someone please explain why the first version doesn't work as expected?


In your first example, you created a var (basically a SpriteNode inside the SpriteNode).

When you instantiate the class like let hero = Hero(....) you now have a SpriteNode called hero, with a property called hero. You can change either. Calling hero.size would change the base hero, and hero.hero.size would change the inside SpriteNode....this is probably not the behavior you were looking for.

The second class looks correct, if you are just trying to create a SpriteNode and modify it. The class is a subclass of SpritNode, so it's already a SpriteNode - no need to create one inside it like the first one.

Hope this helps!