Search code examples
iossprite-kitselectoruitapgesturerecognizer

SpriteKit calling function in another class from GameScene using selector in gesture recognizer


I have a shootLaser function in Laser.swift which is a separate file from GameScene. I'm trying to use a tap gesture recognizer to fire the laser but I'm having trouble with the syntax.

The function in Laser.swift is:

func shootLaser(_ sender: UITapGestureRecognizer, parentNode: SKNode, spriteNode: SKSpriteNode) {

   let laser = SKSpriteNode(imageNamed: "laserBlast")
   parentNode.addChild(laser)

   laser.position = CGPoint(x: spriteNode.position.x, y: spriteNode.position.y)

}

The code in GameScene is something like...

class GameScene {

   let tapRecognizer = UITapGestureRecognizer()
   var laser = Laser()

   override func didMove(to view: SKView) {
   tapRecognizer.addTarget(self, action: #selector(GemScene.laser.shootLaser(_: , parentNode: self, spriteNode: main)))
}

This results in the error, "Expected expression in the list of expressions" but all of the expressions are there...aren't they?


Solution

  • Why not make it easier on yourself and create a separate function for the gesture recognizer?

    override func didMove(to view: SKView) {
        tapRecognizer.addTarget(self, action: #selector(tapRecognized))
    }
    
    func tapRecognized() {
        laser.shootLaser(parentNode: self, spriteNode: main)
    }
    

    This will also simplify the shootLaser method by not requiring that you pass in the gesture recognizer.