我创建了一个敌人 "Fly",它的健康值为2,如果它被子弹击中,我想让它的健康值变为1,下次变为0等等。如果它被子弹击中,我希望特定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;
}
}
如果你想把健康值保留为受保护的字段而不公开的话,就在类Enemy中创建一个公共方法,把它的健康值减少1,然后从碰撞检测块中使用它。