[英]How to change the health of an enemy during runtime?
I have created the enemy "Fly" that starts with 2 health.我创建了以 2 生命值开始的敌人“Fly”。 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.
如果它被子弹击中,我希望特定 Fly 的生命值变为 1,下一次变为 0 等等。我知道如何给 Fly 初始生命值值,但不知道如何在游戏运行时更改它。
I would appreciate help!我会很感激帮助!
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);
}
}
}
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.如果您希望将健康保持为受保护的字段而不将其公开,请为 class Enemy 创建一个公共方法,将其健康降低 1 并从该碰撞检测块中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.