Aphalleon Aphalleon - 6 months ago 18
Swift Question

Adding a sprite to GameScene from another class

I want to add a new sprite to my GameScene within my new file "Constructor.swift" Constructor class. I tried to make a getter within my GameViewController so I could get the current instance of my GameScene and then adding the sprite to it but this doesn't work.

Conclusion;

How can I get the current instance of my GameScene in another class, so my code would be easy maintainable because of all the sprites getting constructed in the constructor class. I want to prevent getting massive amount lines of code in my "GameScene.sks" file.

Answer

You can subclassing with a generic class named for example:

class MyDefaultScene: SKScene {
    var sprite1: SKSpriteNode!
    var followTrack: SKAction!
    var followTrackForever: SKAction!
    var clockWise : Bool = false

    func setDefaultPhisics() {
        self.physicsBody!.mass = 0
        self.physicsBody!.friction = 0
        self.physicsBody!.affectedByGravity = false
        self.physicsBody?.linearDamping = 0
        self.physicsBody?.angularDamping = 0
        self.physicsBody?.restitution = 1
        self.physicsBody?.dynamic = false
    }
    ...
}

class GameScene1: MyDefaulScene {
   override func didMoveToView(view: SKView) {
       print("∙ \(NSStringFromClass(self.dynamicType))")
       print("clockwise: \(self.clockWise)")
   }
}

class GameScene2: MyDefaulScene {
   override func didMoveToView(view: SKView) {
       print("∙ \(NSStringFromClass(self.dynamicType))")
       print("clockwise: \(self.clockWise)")
   }
}
Comments