How to keep enemies of the same class from "sharing" health?

This is probably a pretty simple question. I'm pretty new with fast and I've gone through a couple of books and now I'm trying to learn. I was making a game where zombies were randomly spawned continuously and the player's car ran through them until they died. The problem is that all zombie child nodes seem to have the same health and I'm not sure how to fix it.

My zombie class is initialized with 20 health as below:

class Zombie: SKSpriteNode, GameSprite {
var initialSize:CGSize = CGSize(width: 30, height: 54)
var textureAtlas:SKTextureAtlas = SKTextureAtlas(named: "Zombies")
var health:Int = 20

      

When struck, zombies deal 4 damage on each collision until they die:

func takeDamage() {
    self.health -= 4
    print("zombie has", health, "health")
    if self.health == 0 {
        die()
    }
}

      

It works great for the first zombie and the health decreases five times and it dies, but then the health stays at 0 when the second zombie is spawned and continues to decrease negatively for each zombie as the car continues to collide with them.Of course, none of the zombies after the first never dies because health is already less than zero. I understand why this is happening, but I'm not sure how to reset the health to 20 for each spawning and give each independent zombie health values. I tried to manually set the health variable in my startup function, but it doesn't do anything.

func spawnEnemy(){
    let enemiesToSpawn = arc4random_uniform(11) + 1
    var enemiesSpawned = UInt32(0)
    while enemiesSpawned < enemiesToSpawn {
        var spawnLocationX = player.position.x + CGFloat(arc4random_uniform(200)) + 900
        var spawnLocationY = CGFloat(arc4random_uniform(415)) - 240
        let zombie = Zombie()
        zombie.position = CGPoint(x: spawnLocationX, y: spawnLocationY)
        zombie.zPosition = 1
        zombie.position.x += 33
        zombie.health = 20
        self.addChild(zombie)
        enemiesSpawned += 1

    }

}

      

+3


source to share





All Articles