Search code examples
swiftsprite-kitspriteskaction

Shooting automatically in a Shooter Game (Swift 4 - SpriteKit)


I'm working on a game project with Xcode. I've written the code that makes the ship shoot the projectiles, but I don't know what function to use to make the ship shoot automatically.

Could you help me? Thank you in advance!

Here's my code, from the GameScene :

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

    let projectile = SKSpriteNode(imageNamed: "projectile")
    projectile.zPosition = 1
    projectile.position = CGPoint(x: player.position.x, y: player.position.y)

    projectile.physicsBody = SKPhysicsBody(circleOfRadius: projectile.size.width/2)
    projectile.physicsBody?.isDynamic = true
    projectile.physicsBody?.categoryBitMask = PhysicsCategory.Projectile
    projectile.physicsBody?.contactTestBitMask = PhysicsCategory.Monster
    projectile.physicsBody?.collisionBitMask = PhysicsCategory.None
    projectile.physicsBody?.usesPreciseCollisionDetection = true
    self.addChild(projectile)
    let action = SKAction.moveTo(x: self.frame.width + projectile.size.width, duration: 0.5)

    projectile.run(action, completion: {
        projectile.removeAllActions()
        projectile.removeFromParent()
    })

}

Solution

  • Based on a comment by Jake I am assuming that you want the ship to fire "automatically" not repeating while holding the finger down.

    You can use the update func to control the automatic shooting. in my example the update command fires every 1 second

    private var updateTime: Double = 0
    
    override func update(_ currentTime: TimeInterval) {
    
        if updateTime == 0 {
            updateTime = currentTime
        }
    
        if currentTime - updateTime > 1 {
            self.shoot()
            updateTime = currentTime
        }
    }
    
    func shoot() {
    
        let projectile = SKSpriteNode(imageNamed: "projectile")
        projectile.zPosition = 1
        projectile.position = CGPoint(x: player.position.x, y: player.position.y)
    
        projectile.physicsBody = SKPhysicsBody(circleOfRadius: projectile.size.width/2)
        projectile.physicsBody?.isDynamic = true
        projectile.physicsBody?.categoryBitMask = PhysicsCategory.Projectile
        projectile.physicsBody?.contactTestBitMask = PhysicsCategory.Monster
        projectile.physicsBody?.collisionBitMask = PhysicsCategory.None
        projectile.physicsBody?.usesPreciseCollisionDetection = true
        self.addChild(projectile)
        let action = SKAction.moveTo(x: self.frame.width + projectile.size.width, duration: 0.5)
    
        projectile.run(action, completion: {
            projectile.removeAllActions()
            projectile.removeFromParent()
        })
    }