从健康中扣除

Deducting from health

本文关键字:健康      更新时间:2023-09-26

我有一个船体和护盾,我希望在受到伤害时先从护盾中扣除伤害,然后在空的时候从船体中扣除。但是如果护盾只剩下100,伤害是400,那么船体从1000开始就是700。

这是我设法做的,盾部分工作,但船体算法对我来说太难掌握了。

Player.prototype.deductHealth = function(damage)
{
  var shield = (this.PlayerShield - damage);
  var remainder = (damage - this.PlayerShield);
  var hull = this.PlayerHull;
  if(this.PlayerShield < 0)
   {
     hull = (this.PlayerHull - remainder);
   }
   if(hull <=0)
   {
   hull = 0;
   shield = 0;
   }
   this.PlayerHull = hull;
   this.PlayerShield = shield;
}

我现在不能测试它,但像这样的东西我认为可以工作。

Player.prototype.deductHealth = function(damage)
    {
      var shield = (this.PlayerShield - damage);   
      var remainder = 0;
      if (shield<0) {
          remainder=-shield; 
          shield=0;
      }
      var hull = this.PlayerHull;        
      if(remainder > 0)
       {        
         hull = (this.PlayerHull - remainder);
       }
       if(hull <=0)
       {
          hull = 0;
          shield = 0;
       }
       this.PlayerHull = hull;
       this.PlayerShield = shield;
    }

嗯…试试这个,我认为你有问题,因为你混淆地引用了代表船体和盾强度的本地变量,以及代表船体和盾的成员变量。我的建议是只使用成员变量,像这样:

Player.prototype.deductHealth = function(damage)
{
  var shieldOverkill = (damage - this.PlayerShield);
  this.PlayerShield = this.PlayerShield - damage;
  if ( shieldOverkill > 0 )
  {
      this.PlayerHull = this.PlayerHull - shieldOverkill;
  }
  if( this.PlayerHull < 0)
  {
      this.PlayerHull= 0;
  } 
  if ( this.PlayerShield < 0 )
  {
      this.PlayerShield = 0;
  }

}

让我们一步一步来:

Player.protoype.deductHealth = function (damage) {
   this.PlayerShield -= damage; // First deduct the damage from the shields:
   if (this.PlayerShield < 0) { // If shields are negative
     // Take the damage not absorbed by shields from hull;
     this.PlayerHull += this.PlayerShield;  // note we use + since shields are negative
     this.PlayerShield = 0; // Set shields to 0
     if (this.PlayerHull < 0) { // If hull now negative
       this.PlayerHull = 0; // set to zero.
     }
   }
}

更高级的版本,使用更合适的名称:

Player.prototype.takeHit (damage) {
  if ((this.shields -= damage) < 0) { // Shields exhausted ?
    if ((this.hull += this.shields) < 0) { // Hull exhausted?
       this.hull = 0;
    } 
    this.shields = 0;
  }
}