Richard Parker
Richard Parker

Reputation: 65

Swift: SKAction not working on touch

Ive been trying to follow along swift tutorials and I've come across something extremely frustrating with every tutorial I have tried to follow along with, whenever SKAction is used I cannot follow along with any tutorials because my programs never work. This has happened with MULTIPLE programs and I can never figure it out.

Here is the code for the program:

import SpriteKit
import GameplayKit

class GameScene: SKScene{

let player = SKSpriteNode(imageNamed: "playerShip")

override func didMove(to view: SKView) {

    let background = SKSpriteNode(imageNamed: "background")
    background.size = self.size
    background.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
    background.zPosition = -1
    self.addChild(background)


    player.setScale(1)
    player.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.2)
    player.zPosition = 2
    self.addChild(player)


}

func fireBullet(){

    let bullet = SKSpriteNode(imageNamed: "bullet")
    bullet.setScale(1)
    bullet.zPosition = 1
    bullet.position = player.position

    let moveBullet = SKAction.moveTo(y: self.size.height + bullet.size.height, duration: 1)
    let deleteBullet = SKAction.removeFromParent()
    let bulletSequence = SKAction.sequence([moveBullet, deleteBullet])
    bullet.run(bulletSequence)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    fireBullet()
}

}

Whenever I build and run the program in the simulator everything is fine and the build succeeds. However whenever I click nothing happens, this happens every single time I attempt to do anything with SKAction. I should mention that the FPS at the bottom right corner of my screen changes every time I click, but nothing else happens, the node count stays the same, and the screen remains the same with the bullet not firing.

Here is the tutorial I am attempting to follow along with: https://www.youtube.com/watch?v=mvlwZs2ehLU

Upvotes: 0

Views: 156

Answers (1)

Pierce
Pierce

Reputation: 3158

I noticed you aren't actually adding the bullet sprite to your scene after instantiating it. Make sure to add addChild(bullet). I suggest implementing something like this:

func fireBullet() {

    let bullet = SKSpriteNode(imageNamed: "bullet")
    bullet.setScale(1)
    bullet.zPosition = 1
    bullet.position = player.position
    addChild(bullet)

    let moveBullet = SKAction.moveTo(y: self.size.height + bullet.size.height, duration: 1.0)
    let deleteBullet = SKAction.removeFromParent()
    let bulletSequence = SKAction.sequence([moveBullet, deleteBullet])
    bullet.run(bulletSequence)

}

Upvotes: 4

Related Questions