gpt4 book ai didi

swift - 生成一个敌人

转载 作者:可可西里 更新时间:2023-11-01 02:19:30 24 4
gpt4 key购买 nike

在我的游戏中,我希望每 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

在日志“已调用!”中出现但敌人还没有产生。只是想让你知道,我确实通过以下方式在类创造了敌人:

let enemy2 = SKSpriteNode(imageNamed: "enemy")

有谁知道我如何生成我的第二个敌人?提前致谢!

-文尼

最佳答案

您应该保持简单,只需在 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


}

}

在定位方面,我假设您的场景已经具有正确的尺寸。如果场景未正确初始化并且具有与 View 不同的大小(或更准确地说,不同的纵横比),则可能会发生敌人在生成时离开屏幕的位置。阅读更多 here关于如何正确初始化场景大小。

关于swift - 生成一个敌人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com