-2

我有一个船体和盾牌,我想在受损时承受伤害并首先从盾牌中扣除它,然后当它是空的时从船体中扣除。但是,如果盾牌还剩 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;

}
4

3 回答 3

0

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

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;

    }
于 2013-06-09T17:48:13.177 回答
0

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

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

}

于 2013-06-09T17:53:37.340 回答
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;
  }
}
于 2013-06-09T17:55:47.260 回答