Swift SpriteKit,不能多次发射子弹

时间:2018-06-10 00:23:33

标签: swift sprite-kit swift4

我正在制作一个有太空船的小游戏,你可以发射子弹,当我运行程序并点击发射子弹时,它可以工作,但是当我再次点击时它不会发射。它给了我

Thread 1: signal SIGABRT
当我第二次尝试开火的时候。有人可以帮助我吗?

以下是代码:

import SpriteKit
import GameplayKit
import UIKit

class GameScene: SKScene {

let player = SKSpriteNode(imageNamed: "mySpaceship")
//let stars = SKSpriteNode(imageNamed: "stars")
let bullet = SKSpriteNode(imageNamed: "bullet")

override func didMove(to view: SKView) {
    //print(frame.size.width)
    //print(frame.size.height)

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


}

func fireBullet() {
    bullet.position = player.position
    bullet.zPosition = 1
    self.addChild(bullet)

    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?) {
    print("Fired bullet")
    fireBullet()
}

override func update(_ currentTime: TimeInterval) {
}


}

所有这些代码都在我的GameScene.swift文件中。谢谢!

更新:在查看节点计数器后,我观察到如果我在前一个子弹被删除后触发了一颗子弹(使总节点数为2),子弹就会拍得很好。但是,如果我在删除前一个项目符号(这会使节点数为2)之前射击子弹,程序就会崩溃。反正有没有等待前一个子弹被删除而射击另一颗子弹?

1 个答案:

答案 0 :(得分:1)

您只需要在 fireBullet 方法中初始化Bullet精灵。

func fireBullet() {
    // make sure you initialize bullet here.
    let bullet = SKSpriteNode(imageNamed: "bullet")
    bullet.position = player.position
    bullet.zPosition = 1
    self.addChild(bullet)

    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)
  }