How to add SKSpriteNode to a scene in Swift?

I tried to subclass SKSpriteNode in GameObject , and I would like to create objects outside the class of the game scene. Here is my GameObject code derived from SKSpriteNode :

 import SpriteKit public class GameObject: SKSpriteNode { init( texture: SKTexture?, color: UIColor, size: CGSize, position:CGPoint, name:String ) { objectSize = size; objectName = name; objectSprite = texture; //call superclass here super.init(texture: texture, color: color, size: size); self.position = position; } convenience init(_ _x:CGFloat, _ _y:CGFloat, _ _object:String )// Default initializer { let texture = SKTexture(imageNamed: _object); let position = CGPoint(x:_x, y:_y); self.init( texture: texture,color: UIColor(),size: texture.size(), position: position, name: _object); } //Overloaded initializer with size as extra argument convenience init(_ _x:CGFloat, _ _y:CGFloat, _ _size:Int, _ _object:String) { //size for the SKSpriteNode. let texture = SKTexture(imageNamed: _object); let position = CGPoint(x:_x, y:_y); self.init( texture: texture, color: UIColor(), size: CGSize(width: _size, height: _size),position: position, name: _object); } 

To create a player instance from GameObject , I have to write:

 let player = PlayerShip(100, 100, "PlayerShip") addChild(player) 

However, addChild() does not work outside of gameScene . My goal is to create bullets from the PlayerShip class, but I cannot figure out how to do this. Does anyone have a suggestion?

0
source share
1 answer

If you want to do this outside of GameScene, you will need the kind go global property, which has a link to GameScene. Then you can call:

 myGameScene.AddChild(player) 
+1
source

Source: https://habr.com/ru/post/1241757/


All Articles