如何用Swift中的两个或更多子弹射击

时间:2017-08-22 06:08:23

标签: swift sprite-kit

我正试图找到一种方法,在加电时增加一个以上的子弹。此外,它只是在前4次加电时直接上升,但我希望它在达到5级时有一点角度。

有人可以帮助我使用我目前拥有的以下代码来实现吗?

import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var player: SKSpriteNode!

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

    var gameTimer: Timer!
    var possibleAliens = ["alien", "alien2", "alien3"]

    //bitmask for alien and torpedo's physics body
    let alienCategory:UInt32 = 0x1 << 1
    let photonTorpedoCategory:UInt32 = 0x1 << 0

    //lives
    var livesArray:[SKSpriteNode]!

    //powerUp
    var powerUp: Int = 1


    //didMove
    override func didMove(to view: SKView) {

        addLives()

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

        player = SKSpriteNode(imageNamed: "shuttle")
        player.position = CGPoint(x: self.frame.size.width / 3.6, y: player.size.height / 2 + 20)
        self.addChild(player)

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

    //score and scoreLabel
        scoreLabel = SKLabelNode(text: "Score: 0")
        scoreLabel.position = CGPoint(x: 80, y: self.frame.size.height - 60)
        scoreLabel.fontName = "AmericanTypewriter-Bold"
        scoreLabel.fontSize = 28
        scoreLabel.fontColor = UIColor.white
        score = 0
        self.addChild(scoreLabel)

    //create a timeInterval that can be changed depending on the difficulty 
        var timeInterval = 0.6
        if UserDefaults.standard.bool(forKey: "hard"){
            timeInterval = 0.2
        }



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

    //motion Manager initialization in didMove
        motionManger.accelerometerUpdateInterval = 0.2
    //creatingan acceleration data in didMove
        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 addLives
    func addLives() {
    //initialize livesArray from GameScene
        livesArray = [SKSpriteNode]()

        for live in 1 ... 3 {
            let liveNode = SKSpriteNode(imageNamed: "shuttle")
            liveNode.name = "live\(live)"
            liveNode.position = CGPoint(x: self.frame.size.width - CGFloat((4-live)) * liveNode.size.width, y: self.frame.size.height - 60)
            self.addChild(liveNode)
            livesArray.append(liveNode)

        }
    }


    //func addAlien
    func addAlien() {

    //using GK, pick possibleAliens[arrays] randomly, and shuffle
        possibleAliens = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possibleAliens) as! [String]

    //bring the aliens to random position
        let alien = SKSpriteNode(imageNamed: possibleAliens[0])
        let randomAlienPosition = GKRandomDistribution(lowestValue: 0, highestValue: 414)

    //make the position constant, use randomAlien and get next integer and use CGFloat then set alien position
        let position = CGFloat(randomAlienPosition.nextInt())
        alien.position = CGPoint(x: position, y: self.frame.size.height + alien.size.height)

    //physicsBody of addAlien
        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)

    //make aliens move
        let animationDuration: TimeInterval = 6

    //SKAction to alien will make alien move from top to bottom of the screen, then remove alien from screen and from parent so it doesnt consume too much memory
        var actionArray = [SKAction]()
        actionArray.append(SKAction.move(to: CGPoint(x: position, y: -alien.size.height), duration: animationDuration))

    //THIS ACTION WILL SEE IF IT REACHES THE FINAL DESTINATION BEFORE IT GETS ERASED AND TAKES A LIFE
    //A RUN ACTION THAT WILL PLAY SOUND WHEN PLAYER LOSES SOUND.
        actionArray.append(SKAction.run{
            self.run(SKAction.playSoundFileNamed("loose.mp3", waitForCompletion: false))

            if self.livesArray.count > 0 {
                let liveNode = self.livesArray.first
                liveNode!.removeFromParent()
                self.livesArray.removeFirst()

                if self.livesArray.count == 0{
                    let transition = SKTransition.flipHorizontal(withDuration: 0.5)
                    let gameOver = SKScene(fileNamed: "GameOverScene") as! GameOverScene
                    gameOver.score = self.score
                    self.view?.presentScene(gameOver, transition: transition)

                }
            }
        })

        actionArray.append(SKAction.removeFromParent())
    //make a run function on the alien to pass allong actionArray
        alien.run(SKAction.sequence(actionArray))
    }


     //fire fireTorpedo when tapped
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        fireTorpedo()
    }


    //func FireTorpedo or bullet
    func fireTorpedo(){
    //adds sound, image and position of the torpedo
        self.run(SKAction.playSoundFileNamed("torpedo.mp3", waitForCompletion: false))
        let torpedoNode = SKSpriteNode(imageNamed: "torpedo")

    //powerUp switch
        switch (powerUp)
        {
        case 1:
            torpedoNode.position.x = player.position.x
            torpedoNode.position.y = player.position.y
        case 2:
            torpedoNode.position.y = player.position.y
            torpedoNode.position.x = player.position.x - 10
            torpedoNode.position.x = player.position.x + 10
        default:
            print("out of torpedo ammo")
            break
        }

        torpedoNode.position.y += 5
    //add physicsBody for torpedo just like the aliens
        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)

    //add animation like in alien
        let animationDuration: TimeInterval = 0.3
    //make torpedo move up and disappear
        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())
    //run the torpedo
        torpedoNode.run(SKAction.sequence(actionArray))
    }

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

    //check if two bodies touch
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        } else {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }
    //to findout which body is the torpedo and which is alien
        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?){
        if let explosion = SKEmitterNode(fileNamed: "Explosion"){

            if let alien = alienNode{
                explosion.position = alien.position
            }
            self.addChild(explosion)
            self.run(SKAction.playSoundFileNamed("explosion.mp3", waitForCompletion: false))

            if let torpedo = torpedoNode{
                torpedo.removeFromParent()
            }
            if let alien = alienNode{
                alien.removeFromParent()
            }

        //see the explosion effect longer and not disappear immediately with run function with action and completion handler
            self.run(SKAction.wait(forDuration: 2)){
                explosion.removeFromParent()
            }
    //add and update score
            score += 5
        }
    }


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

0 个答案:

没有答案