从健康中扣除

时间:2013-06-09 17:40:37

标签: javascript canvas

我有一个船体和盾牌,我想要在受到损坏的时候先从盾牌中扣除它,然后再将其从船体上取下来。但是如果盾牌剩下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;

}

3 个答案:

答案 0 :(得分: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;

    }

答案 1 :(得分: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;
  }

}

答案 2 :(得分: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;
  }
}