0
votes

Hi I'm kinda new to Swift and SpriteKit in general, anyway I am trying to make a game for a project. I have dragged a button onto the Main.storyboard and connected its code to the GameViewController.swift

My button code and current attempt is below,

@IBAction func TroopB1(_ sender: AnyObject) {
    let newGS = GameScene()
    newGS.spawnEnemy()
}

Now what I want to do is call a function in the GameScene.swift which creates a SKSpriteNode (defined in my Player Class) and add it in Game.

The code for the function which is in GameScene.swift is below,

func spawnTroop() {
    let newTroop = Player(imageNamed: "Troop1")
    newTroop.loadtroop()
    self.addChild(newTroop)
}

The Class Player is defined as a SKSpritNode and loadtroop just defines some attributes and the SKSpritenodes physics body.

Can anyone help in telling me how to call the spawnTroop() function which is in the GameScene from the button function - TroopB1 - in the GameViewController.swift and create a new SKSpritenode in my Game as all attempts so far have been unsuccessful?

1
spawnEnemy in the first code snippet should be spawnTroop right? - Sweeper

1 Answers

0
votes

You called spawnEnemy() after you created a new scene like this:

let newGS = GameScene()

The new scene you created is not the same scene as the one presented in the SKView. You spawned a troop in this scene, not the scene presented.

One way to access the scene presented is this:

((self.view as? SKView)?.scene as? GameScene).spawnTroop()

We first access the view that the VC is controlling as a SKView, then access the scene presented in the view as a GameScene, then we call the method.