我需要在玩家碰撞时更改敌人SKSpriteNode
的图像,但在游戏中我会有很多敌人,而我只想更改所选择的敌人。
Enemy.name
是生命的数量,我不知道我是否可以这样做。
func setupPlayer(){
player = SKSpriteNode(imageNamed: "ball")
player.anchorPoint = CGPoint(x: 0.5, y: 0.5)
player.position = CGPoint(x: size.width/2, y: 60)
player.zPosition = Layer.Player.rawValue
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.mass = 1
player.physicsBody?.restitution = 0.7
player.physicsBody?.dynamic = true
player.physicsBody?.categoryBitMask = playerCategory
player.physicsBody?.contactTestBitMask = enemyCategory
worlNode.addChild(player)
nuevoPlayerControl = true
}
func setupEnemy(){
if nuevoPlayerControl == true && nuevoPlayer == true{
enemy = SKSpriteNode(imageNamed: "ball")
enemy.anchorPoint = CGPoint(x: 0.5, y: 0.5)
enemy.zPosition = Layer.Player.rawValue
enemy.position = CGPoint(x: 250, y: 300)
enemy.physicsBody?.mass = 1
enemy.zRotation = player.zRotation
enemy.size = player.size
enemy.physicsBody = SKPhysicsBody(circleOfRadius: enemy.size.width/2)
enemy.physicsBody?.friction = 1
enemy.physicsBody?.dynamic = true
enemy.physicsBody?.categoryBitMask = enemyCategory
enemy.physicsBody?.contactTestBitMask = playerCategory
enemy.name = "3"
worlNode.addChild(enemy)
}
}
func didBeginContact(contact: SKPhysicsContact) {
var body1 : SKPhysicsBody!
var body2 : SKPhysicsBody!
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
body1 = contact.bodyA
body2 = contact.bodyB
}
else {
body1 = contact.bodyB
body2 = contact.bodyA
}
if body1.categoryBitMask == playerCategory && body2.categoryBitMask == enemyCategory {
//here the enemy lose a live and the image should change
let lives = body2.node?.name
if lives! == "3" {
body2.node?.name = "2"
}
if lives! == "2" {
body2.node?.name = "1"
}
if lives! == "1" {
body2.node?.removeFromParent()
}
print(lives)
}
}
答案 0 :(得分:1)
如果需要,您可以随时为从SKSpriteNode继承的敌人编写自定义类,您可以在其中拥有名为numLives
的属性,这样您就可以使用名称字符串来实现此目的,并通过{{获取生命数量1}}。最简单的方法可能是使用enemy.numLives
字符串的第一部分来表示生命数量,第二部分用于你的敌人识别,当你需要生命或名字的数量时,你只需要解析它就可以得到什么你要。例如:
name
然后,如果您需要访问它,可以使用for-in解析/循环,或者使用//when you create an enemy:
enemy.name = "3 bigEnemy"
获取所需的字符串部分:
subStringWithRange
您在碰撞时更改图像的方向正确。你剩下要做的就是改变//to get the number of lives:
let lives = enemy.name.substringWithRange(NSRangeMake(0, 1))
//to get the name of the enemy:
let name = enemy.name.substringWithRange(NSRangeMake(3, enemy.name.length))
的纹理。如果您有图像,只需使用:
body.node