繁体   English   中英

如何在运行时改变敌人的生命值?

[英]How to change the health of an enemy during runtime?

我创建了以 2 生命值开始的敌人“Fly”。 如果它被子弹击中,我希望特定 Fly 的生命值变为 1,下一次变为 0 等等。我知道如何给 Fly 初始生命值值,但不知道如何在游戏运行时更改它。

我会很感激帮助!

游戏元素.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);
        }
    }
}

敌人.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;
    }
}

您已经有有效的碰撞检测,似乎可以在击中时立即杀死敌人。 尝试将其更改为:

    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;
        }
    }

如果您希望将健康保持为受保护的字段而不将其公开,请为 class Enemy 创建一个公共方法,将其健康降低 1 并从该碰撞检测块中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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