[英]How to change the health of an enemy during runtime?
我創建了以 2 生命值開始的敵人“Fly”。 如果它被子彈擊中,我希望特定 Fly 的生命值變為 1,下一次變為 0 等等。我知道如何給 Fly 初始生命值值,但不知道如何在游戲運行時更改它。
我會很感激幫助!
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;
}
}
您已經有有效的碰撞檢測,似乎可以在擊中時立即殺死敵人。 嘗試將其更改為:
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.