【发布时间】:2017-07-13 04:39:26
【问题描述】:
这是我的代码:
func bombTowerTurnShoot() {
var prevDistance:CGFloat = 1000000
var closesetZombie = zombieArray[0]
self.enumerateChildNodes(withName: "bomb tower") {
node, stop in
if self.zombieArray.count > 0 {
for zombie in self.zombieArray {
if let bombTower = node as? SKSpriteNode {
let angle = atan2(closesetZombie.position.x - bombTower.position.x , closesetZombie.position.y - bombTower.position.y)
let actionTurn = SKAction.rotate(toAngle: -(angle - CGFloat(Double.pi/2)), duration: 0.2)
bombTower.run(actionTurn)
let turretBullet = SKSpriteNode(imageNamed: "Level 1 Turret Bullet")
turretBullet.position = bombTower.position
turretBullet.zPosition = 20
turretBullet.size = CGSize(width: 20, height: 20)
//turretBullet.setScale (frame.size.height / 5000)
turretBullet.physicsBody = SKPhysicsBody(circleOfRadius: max(turretBullet.size.width / 2, turretBullet.size.height / 2))
turretBullet.physicsBody?.affectedByGravity = false
turretBullet.physicsBody!.categoryBitMask = PhysicsCategories.Bullet //new contact
turretBullet.physicsBody!.collisionBitMask = PhysicsCategories.None
turretBullet.physicsBody!.contactTestBitMask = PhysicsCategories.Zombie
self.addChild(turretBullet)
var dx = CGFloat(closesetZombie.position.x - bombTower.position.x)
var dy = CGFloat(closesetZombie.position.y - bombTower.position.y)
let magnitude = sqrt(dx * dx + dy * dy)
dx /= magnitude
dy /= magnitude
let vector = CGVector(dx: 4.0 * dx, dy: 4.0 * dy)
func fire () {
turretBullet.physicsBody?.applyImpulse(vector)
}
func deleteBullet() {
turretBullet.removeFromParent()
}
turretBullet.run(SKAction.sequence([SKAction.wait(forDuration: 0), SKAction.run(fire), SKAction.wait(forDuration: 2.0), SKAction.run(deleteBullet) ]))
let distance = hypot(zombie.position.x - bombTower.position.x, zombie.position.y - bombTower.position.y)
if distance < prevDistance {
prevDistance = distance
closesetZombie = zombie
}
}
}
}
}
}
这段代码的作用是将炮塔转向最近的僵尸并朝它开枪。据我所知,炮塔转向最近的僵尸(如果你能说出这段代码是否真的完成了,我想知道)。我遇到的更大问题是炮塔有时会发射不止一颗子弹。我认为这是因为它试图向阵列中的所有僵尸开火,而不是指定的僵尸(离塔最近)。我怎样才能让炮塔只射击最近的僵尸?
class GameScene: SKScene, SKPhysicsContactDelegate {//new contact
var zombieArray:[SKSpriteNode] = []
...
...
}
我将所有僵尸添加到数组中,一旦它们死亡,我会将它们从数组中删除。
【问题讨论】:
-
我们需要zombieArray声明的代码。
-
刚刚添加,希望对您有帮助。
-
它确实对这个问题有所帮助,但我已经在下面回答了你的问题。您是否了解将操作分为两种方法的必要性?
findClosestZombie然后fireAtZombie。现在,您正在对循环的每次迭代以及self.enumeratedChildNodes的每次迭代都进行这两项操作 -
哦,对不起,我没有看到你的回答,我的错。
标签: swift sprite-kit skspritenode