迅捷2
SpriteKit
因此,我使用以下代码随机产生敌人,然后将其移向玩家。但是由于某种原因,只有第一个敌人向玩家移动,其余的敌人什么也没有做。我对此并不陌生,因此所有细节都将有所帮助。
在didmovetoview下:
let wait = SKAction.waitForDuration(3, withRange: 2)
let spawn = SKAction.runBlock {
let Enemy = SKSpriteNode(imageNamed: "Enemy.png")
Enemy.size.height = (70) //138
Enemy.size.width = (49) //99
Enemy.position = CGPointMake(CGRectGetWidth(self.frame) - 100 , CGRectGetHeight(self.frame) - 100)
Enemy.physicsBody = SKPhysicsBody (rectangleOfSize: Enemy.size)
Enemy.physicsBody!.dynamic = true
Enemy.physicsBody!.allowsRotation = false
Enemy.physicsBody!.friction = 0
Enemy.physicsBody!.restitution = 0
Enemy.physicsBody!.linearDamping = 1
Enemy.physicsBody!.angularDamping = 1
Enemy.name = "Enemy"
Enemy.zPosition = 3
self.addChild(Enemy)
self.EnemyExists=true
}
let sequence = SKAction.sequence([wait, spawn])
self.runAction(SKAction.repeatActionForever(sequence))
在更新功能下:
let Enemy = childNodeWithName("Enemy") as! SKSpriteNode
let Player = childNodeWithName("Player") as! SKSpriteNode
if EnemySpeed == OriginalEnemySpeed {
let impulseVector = CGVector(dx: (Player.position.x - Enemy.position.x)/200, dy: (Player.position.y - Enemy.position.y)/200)
Enemy.physicsBody?.applyImpulse(impulseVector)
}
if Enemy.position.x + Enemy.size.width / 4 > size.width {
Enemy.position.x = Enemy.size.width / 4
}
else if Enemy.position.x + Enemy.size.width / 4 < 0 {
Enemy.position.x = size.width - Enemy.size.width / 4
}
if Enemy.position.y + Enemy.size.height / 4 > size.height {
Enemy.position.y = Enemy.size.height / 4
}
else if Enemy.position.y + Enemy.size.height / 4 < 0 {
Enemy.position.y = size.height - Enemy.size.height / 4
}
EnemySpeed-=1
if EnemySpeed < 1 {
EnemySpeed = OriginalEnemySpeed
}
最佳答案
childNodeWithName("Enemy")
将仅拾取场景中称为Enemy
的第一个精灵。
您需要使用enumerateChildNodesWithName
遍历所有被称为敌人的精灵:
enumerateChildNodesWithName("Enemy") {
node, stop in
let Enemy = node as! SKSpriteNode
// Your enemy movement/update code here
}
如果应该引用
EnemySpeed
变量来引用您当前正在处理的sprite的速度,则必须对其进行处理,因为它只是单个实例变量,而不是该sprite的属性。您可能需要使用Enemy.physicsBody.velocity,它是CGVector,因此要将其转换为所需的速度:enemySpeedX = enemy.physicsbody.velocity.dx
enemySpeedY = enemy.physicsbody.velocity.dy
enemySpeed = sqrt(enemySpeedX* enemySpeedX + enemySpeedY* enemySpeedY)
同时检查您的命名标准;大多数事情应该是驼峰式的,所以
Enemy
应该是enemy
,OriginalEnemySpeed
应该是originalEnemySpeed
等。关于ios - 如何控制多个具有相同名称的Sprite Kit节点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36928183/