产卵的敌人

时间:2015-08-09 23:14:08

标签: swift sprite-kit nstimer

在我的游戏中,我希望敌人每10秒产生一次。我试图通过在GameViewController中编写

来实现这一点
var secondEnemyTimer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "secondEnemyFunction", userInfo: nil, repeats: false)
viewWillLayoutSubviews方法中的

。然后在secondEnemyFunction中写道:

let skView = self.view as! SKView
    let gameScene = GameScene(size: skView.bounds.size)

    gameScene.enemy2Function()

然后在GameScene类的enemy2Function中写道:

 println("Called!")

    enemy2.name = enemyCategoryName

    enemy2.size.width = 57
    enemy2.size.height = 57

    let randomX = randomInRange(Int(CGRectGetMinX(self.frame)), hi: Int(CGRectGetMaxX(self.frame)))
    let randomY = randomInRange(Int(CGRectGetMinY(self.frame)), hi: Int(CGRectGetMaxY(self.frame)))
    let randomPoint = CGPoint(x: randomX, y: randomY)
    enemy2.position = randomPoint

    self.addChild(enemy2)

    enemy2.physicsBody = SKPhysicsBody(circleOfRadius: enemy1.size.width / 2)
    enemy2.physicsBody?.friction = 0
    enemy2.physicsBody?.restitution = 1
    enemy2.physicsBody?.linearDamping = 0
    enemy2.physicsBody?.allowsRotation = false

    enemy2.physicsBody?.applyImpulse(CGVectorMake(50, -50))

    enemy2.physicsBody?.categoryBitMask = enemyCategory

在日志“Called!”中看来敌人没有产生。只是你知道我确实通过这样做来创造了最高级的敌人:

let enemy2 = SKSpriteNode(imageNamed: "enemy")

有谁知道我如何能够产生我的第二个敌人?提前谢谢!

-Vinny

1 个答案:

答案 0 :(得分:1)

你应该保持简单,只需在GameScene中做所有事情。另一件事是放弃NSTimer并使用SKAction产生敌人。 NSTimer不尊重场景的暂停状态,因此最终可能会遇到麻烦。这就是你如何使用SKAction产生敌人:

<强> GameScene.swift:

import SpriteKit

class GameScene: SKScene {


    override func didMoveToView(view: SKView) {

        generateEnemies()
    }

    func stopGeneratingCoins(){


        if(self.actionForKey("spawning") != nil){removeActionForKey("spawning")}

    }

    func generateEnemies(){

        if(self.actionForKey("spawning") != nil){return}



        let timer = SKAction.waitForDuration(10)

        //let timer = SKAction.waitForDuration(10, withRange: 3)//you can use withRange to randomize duration


        let spawnNode = SKAction.runBlock {


            var enemy = SKSpriteNode(color: SKColor.greenColor(), size:CGSize(width: 40, height:40))
            enemy.name = "enemy" // name it, so you can access all enemies at once.

            //spawn enemies inside view's bounds
            let spawnLocation = CGPoint(x:Int(arc4random() % UInt32(self.frame.size.width - enemy.size.width/2) ),
                y:Int(arc4random() %  UInt32(self.frame.size.height - enemy.size.width/2)))

            enemy.position = spawnLocation


            self.addChild(enemy)

            println(spawnLocation)

        }

        let sequence = SKAction.sequence([timer, spawnNode])


        self.runAction(SKAction.repeatActionForever(sequence) , withKey: "spawning") // run action with key so you can remove it later


    }

}

说到定位,我假设你的场景已经有了正确的尺寸。如果场景未正确初始化并且具有与视图不同的大小(或更精确地,不同的宽高比),则可能发生敌人在生成时获得屏幕外位置。阅读更多关于如何正确初始化场景大小的here