我找到了关于如何让敌人向玩家移动的this答案。如果GameScene
上有一个敌人,那就完美了。但是,如果我将另一个敌人添加到场景中,则只有一个移动而另一个静止。
以下是我到目前为止所有设置的代码。
var player: SKSpriteNode?
var spawnZombie = SKSpriteNode()
override func didMove(to view: SKView) {
playerTexture = SKTexture(imageNamed: "player_2")
player = SKSpriteNode(texture: playerTexture)
player?.name = "player"
player?.position = (pSpawnPoint?.position)!
player?.setScale(0.5)
self.addChild(player!)
randomEnemy()
randomEnemy()
}
这就是我的敌人的设置方式
func randomEnemy(){
spawnPoint0 = childNode(withName: "spawnPoint_0") as? SKSpriteNode
spawnPoint1 = childNode(withName: "spawnPoint_1") as? SKSpriteNode
spawnPoint2 = childNode(withName: "spawnPoint_2") as? SKSpriteNode
// Set up enemies
enemy = SKSpriteNode(imageNamed: "enemy_2")
enemy.name = "enemy"
enemy.setScale(0.5)
enemy.zPosition = 10
enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.categoryBitMask = PhysicsCatagory.Enemy
enemy.physicsBody?.collisionBitMask = PhysicsCatagory.None
enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.Player
enemy.physicsBody?.isDynamic = true
enemy.physicsBody?.affectedByGravity = false
let choice = Int(arc4random_uniform(3))
switch choice {
case 0:
enemy.position = (spawnPoint0?.position)!
self.addChild(enemy)
break
case 1:
enemy.position = (spawnPoint1?.position)!
self.addChild(enemy)
break
case 2:
enemy.position = (spawnPoint2?.position)!
self.addChild(enemy)
break
default:
print("something went wrong")
}
}
override func update(_ currentTime: TimeInterval) {
let location = player?.position
//Aim
let dx = (location?.x)! - enemy.position.x
let dy = (location?.y)! - enemy.position.y
let angle = atan2(dy, dx)
enemy.zRotation = angle - 3 * .pi/2
//Seek
let velocityX = cos(angle) * enemySpeed
let velocityY = sin(angle) * enemySpeed
enemy.position.x += velocityX
enemy.position.y += velocityY
}
任何想法为什么每当我运行两次这个功能时,只有一个敌人会移动?提前致谢。
答案 0 :(得分:2)
你将两个敌人放在同一个敌人变量中。所以当你试图移动敌人时,你基本上是移动分配给该变量的最后一个。
你需要做的就是把它们放在一个数组中,然后从阵列中移出所有的敌人。
let enemies = [SKSpriteNode]()
func randomEnemy() {
//...other code blah blah blah
enemies.append(enemy)
}
并在更新功能
中override func update(_ currentTime: TimeInterval) {
let location = player?.position
for enemy in enemies {
//Aim
let dx = (location?.x)! - enemy.position.x
let dy = (location?.y)! - enemy.position.y
let angle = atan2(dy, dx)
enemy.zRotation = angle - 3 * .pi/2
//Seek
let velocityX = cos(angle) * enemySpeed
let velocityY = sin(angle) * enemySpeed
enemy.position.x += velocityX
enemy.position.y += velocity
}
}
现在你可能想要查看子类的敌人并在该类中具有移动功能,但这超出了你的问题的范围。这应该让你开始。