当精神被迅速移除时停止发生功能3

问题描述 投票:0回答:1

当我的灵死亡或被removeFromParent()命令移除时,我遇到了问题。精神被取消成功,但即使圣灵不存在,我仍然可以射击导弹。我的GameScene.swft代码如下:

import SpriteKit
import GameplayKit
import CoreMotion

class GameScene: SKScene, SKPhysicsContactDelegate {

var starfield:SKEmitterNode!
var player = SKSpriteNode()

var scoreLabel:SKLabelNode!
var score:Int = 0 {
    didSet {
        scoreLabel.text = "Score: \(score)"
    }
}

var gameTimer:Timer!

var possibleAliens = ["alien", "alien2", "alien3"]

let alienCategory:UInt32 = 0x1 << 1
let photonTorpedoCategory:UInt32 = 0x1 << 0
let photonshuttleCategory:UInt32 = 0x1 << 0
let photonalienCategory: UInt32 = 0x1 << 0
let shuttleCategory:UInt32 = 0x1 << 1



let motionManger = CMMotionManager()
var xAcceleration:CGFloat = 0

override func didMove(to view: SKView) {

    self.physicsWorld.contactDelegate = self

    starfield = SKEmitterNode(fileNamed: "Starfield")
    starfield.position = CGPoint(x: 0, y: 1472)
    starfield.advanceSimulationTime(10)
    self.addChild(starfield)

    func restart(){

        let mainStoryboard = UIStoryboard(name: "Start", bundle: nil)
        let vc = mainStoryboard.instantiateViewController(withIdentifier: "Start")
        self.view?.window?.rootViewController?.present(vc, animated: true, completion: nil)

    }


    starfield.zPosition = -1

    player = SKSpriteNode(imageNamed: "shuttle")

    player.position = CGPoint(x: self.frame.size.width / 2, y: player.size.height / 2 + 20)


    var Ghost = player

    Ghost.physicsBody = SKPhysicsBody(circleOfRadius: (Ghost.frame.height) / 2)
    Ghost.physicsBody?.categoryBitMask = photonshuttleCategory
    Ghost.physicsBody?.collisionBitMask = 0
    Ghost.physicsBody?.contactTestBitMask = alienCategory
    Ghost.physicsBody?.isDynamic = true
    Ghost.physicsBody?.usesPreciseCollisionDetection = true


    self.addChild(player)

    self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
    self.physicsWorld.contactDelegate = self

    scoreLabel = SKLabelNode(text: "Score: 0")
    scoreLabel.position = CGPoint(x: 100, y: self.frame.size.height - 60)
    scoreLabel.fontName = "AmericanTypewriter-Bold"
    scoreLabel.fontSize = 36
    scoreLabel.fontColor = UIColor.white
    score = 0
    if score >= 100{

        player = SKSpriteNode(imageNamed: "Spaceship")

    }



    self.addChild(scoreLabel)


    gameTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(addAlien), userInfo: nil, repeats: true)

    if score >= 100{

        gameTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(addAlien), userInfo: nil, repeats: true)

    }

    motionManger.accelerometerUpdateInterval = 0.1
    motionManger.startAccelerometerUpdates(to: OperationQueue.current!) { (data:CMAccelerometerData?, error:Error?) in
        if let accelerometerData = data {
            let acceleration = accelerometerData.acceleration
            self.xAcceleration = CGFloat(acceleration.x) * 0.75 + self.xAcceleration * 0.25
        }
    }



}



func addAlien () {
    possibleAliens = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possibleAliens) as! [String]

    let alien = SKSpriteNode(imageNamed: possibleAliens[0])

    let randomAlienPosition = GKRandomDistribution(lowestValue: 0, highestValue: 414)
    let position = CGFloat(randomAlienPosition.nextInt())

    alien.position = CGPoint(x: position, y: self.frame.size.height + alien.size.height)

    alien.physicsBody = SKPhysicsBody(rectangleOf: alien.size)
    alien.physicsBody?.isDynamic = true

    alien.physicsBody?.categoryBitMask = alienCategory
    alien.physicsBody?.contactTestBitMask = photonTorpedoCategory
    alien.physicsBody?.collisionBitMask = 0

    self.addChild(alien)

    let animationDuration:TimeInterval = 6

    var actionArray = [SKAction]()


    actionArray.append(SKAction.move(to: CGPoint(x: position, y: -alien.size.height), duration: animationDuration))
    actionArray.append(SKAction.removeFromParent())

    alien.run(SKAction.sequence(actionArray))


}


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

    let delay = SKAction.wait(forDuration: 2.6)
    self.run(delay)

    fireTorpedo()

}


func fireTorpedo() {

    self.run(SKAction.playSoundFileNamed("torpedo.mp3", waitForCompletion: false))

    let torpedoNode = SKSpriteNode(imageNamed: "torpedo")
    torpedoNode.position = player.position
    torpedoNode.position.y += 60

    torpedoNode.physicsBody = SKPhysicsBody(circleOfRadius: torpedoNode.size.width / 2)
    torpedoNode.physicsBody?.isDynamic = true

    torpedoNode.physicsBody?.categoryBitMask = photonTorpedoCategory
    torpedoNode.physicsBody?.contactTestBitMask = alienCategory
    torpedoNode.physicsBody?.collisionBitMask = 0
    torpedoNode.physicsBody?.usesPreciseCollisionDetection = true

    self.addChild(torpedoNode)

    let animationDuration:TimeInterval = 0.3


    var actionArray = [SKAction]()

    actionArray.append(SKAction.move(to: CGPoint(x: player.position.x, y: self.frame.size.height + 10), duration: animationDuration))
    actionArray.append(SKAction.removeFromParent())

    torpedoNode.run(SKAction.sequence(actionArray))



}


func didBegin(_ contact: SKPhysicsContact) {
    var firstBody:SKPhysicsBody
    var secondBody:SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if (firstBody.categoryBitMask & photonTorpedoCategory) != 0 && (secondBody.categoryBitMask & alienCategory) != 0 {
       torpedoDidCollideWithAlien(torpedoNode: firstBody.node as! SKSpriteNode, alienNode: secondBody.node as! SKSpriteNode)
    }


}


func torpedoDidCollideWithAlien (torpedoNode:SKSpriteNode, alienNode:SKSpriteNode) {

    let explosion = SKEmitterNode(fileNamed: "Explosion")!
    explosion.position = alienNode.position
    self.addChild(explosion)

    self.run(SKAction.playSoundFileNamed("explosion.mp3", waitForCompletion: false))

    torpedoNode.removeFromParent()
    alienNode.removeFromParent()


    self.run(SKAction.wait(forDuration: 2)) { 
        explosion.removeFromParent()
    }

    score += 5



}

func hitdidBegin(_ contact: SKPhysicsContact) {
    var firstBody:SKPhysicsBody
    var secondBody:SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if (firstBody.categoryBitMask & photonshuttleCategory) != 0 && (secondBody.categoryBitMask & alienCategory) != 0 {
        spaceshipDidCollideWithNode(alienNode: secondBody.node as! SKSpriteNode, spaceShip: firstBody.node as! SKSpriteNode)
    }

}


func spaceshipDidCollideWithNode (alienNode:SKSpriteNode, spaceShip:SKSpriteNode){

    let explosion = SKEmitterNode(fileNamed: "Explosion")
    explosion?.position = alienNode.position
    self.addChild(explosion!)

    self.run(SKAction.playSoundFileNamed("explosion.mp3", waitForCompletion: false))

    alienNode.removeFromParent()
    spaceShip.removeFromParent()

    self.run(SKAction.wait(forDuration: 2)){
        explosion?.removeFromParent()

    }
    score = 0



}

override func didSimulatePhysics() {

    player.position.x += xAcceleration * 50

    if player.position.x < -20 {
        player.position = CGPoint(x: self.size.width + 20, y: player.position.y)
    }else if player.position.x > self.size.width + 20 {
        player.position = CGPoint(x: -20, y: player.position.y)
    }

}


override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
   }
}

我想要发生的是当Ghost / shuttle / player被移除时不会调用fireTorpedo函数。

谢谢。

xcode8
1个回答
1
投票

有几种方法可以达到你想要的效果

1)你检查球员的父母属性是否为零并且如果是,则不会发射鱼雷(我不确定这是最好的方式)

  func fireTorpedo() {
   guard player.parent != nil else { return }

   ...
}

2)您可以将您的播放器设为可选属性

class GameScene: SKScene {

     var player: SKSpriteNode?

     override func didMove(to view: SKView) {
        player = SKSpriteNode()
        ...
     }
}

当你删除它时,将其设置为零

player = nil

如果玩家是零,那么就不要发射鱼雷

func fireTorpedo() {
   guard player != nil else { return }

   ...
}

3)您可以在GameScene类中创建另一个属性

var isPlayerRemoved = false

当您移除播放器时,只需将其设置为true即可

isPlayerRemoved = true

而不是调整您的鱼雷功能

func fireTorpedo() {
   guard !isPlayerRemoved else { return }

   ...
}

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.