简体   繁体   中英

How to change the health of an enemy during runtime?

I have created the enemy "Fly" that starts with 2 health. If it gets hit by a bullet I want the health of the specific Fly to change to 1, the next time to 0 etc. I know how to give Fly an initial health value, but not how to change it while the game is running.

I would appreciate help!

GameElements.cs

public static State RunUpdate(ContentManager content, GameWindow window, 
    GameTime gameTime)
{
    background.Update(window);
    player.Update(window, gameTime);

    foreach (Enemy e in enemies.ToList())
    {
        foreach (Bullet b in player.Bullets.ToList())
        {
            if (e.CheckCollision(b))
            {
                e.IsAlive = false;
            }
        }

        if (e.IsAlive)
        {
            if (e.CheckCollision(player))
            {
                player.IsAlive = false;
            }

            e.Update(window);
        }
        else
        {
            enemies.Remove(e);
        }
    }
}

Enemy.cs

public abstract class Enemy : PhysicalObject
{
    protected int health;

    public Enemy(Texture2D texture, float X, float Y, float speedX, 
        float speedY, int health) : base(texture, X, Y, 6f, 0.3f)
    {
        // Without this, the health of the Fly is set to 0 I believe. 
        // Is there a more correct way to do it?
        this.health = health; 
    }

    public abstract void Update(GameWindow window);

}

class Fly : Enemy
{
    public Fly(Texture2D texture, float X, float Y) : base(texture, X, Y, 0f, 3f, 2)
    { }

    public override void Update(GameWindow window)
    {
        vector.Y += speed.Y * 7;

        if (vector.X > window.ClientBounds.Width - texture.Width || vector.X < 0)
            speed.X *= -1;

        if (vector.Y > window.ClientBounds.Height - texture.Height || vector.Y < 0)
            speed.Y *= -1;
    }
}

You already have working collision detection that seems to instantly kill the enemy on hit. Try changing it to:

    foreach (Bullet b in player.Bullets.ToList())
    {
        if (e.CheckCollision(b))
        {
            e.Health--
            if(e.Health <= 0) //Health of 0 means dead right?
                e.IsAlive = false;
        }
    }

If you wish to keep health as protected field and not make it public, create a public method to class Enemy that reduces its health by one and use it from that collision detection block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM