更好的方式来继续而不是重复

时间:2015-01-09 00:00:55

标签: javascript

我认为有一种更好的方法,然后为每一个重复相同的过程?

和碰撞方法一样,碰撞方法只适用于中心碰撞,这真的很好。

var ereset = function(){
    //Attacker 1
    att1.x = 0 + (Math.random() * (canvas.width - 64));
    att1.y = -60 ;  
    //Attacker 2
    att2.x = 0 + (Math.random() * (canvas.width - 64));
    att2.y = -60 ;      
    //Attacker 3
    att3.x = 0 + (Math.random() * (canvas.width - 64));
    att3.y = -60 ;  
    //Attacker 4
    att4.x = 0 + (Math.random() * (canvas.width - 64));
    att4.y = -60 ;  
    //Attacker 5
    att5.x = 0 + (Math.random() * (canvas.width - 64));
    att5.y = -60 ;  
}



  if (
        hero.x <= (att1.x + 20 || att1.x + 32)
        && att1.x <= (hero.x + 20 || att1.x + 32)
        && hero.y <= (att1.y + 20 || att1.y - 32)
        && att1.y <= (hero.y + 20 || att1.y - 32)
    ){
        end();
    } else if(
        hero.x <= (att2.x + 20 || att2.x + 32)
        && att2.x <= (hero.x + 20 || att2.x + 32)
        && hero.y <= (att2.y + 20 || att2.y - 32)
        && att2.y <= (hero.y + 20 || att2.y - 32)
    ){
        end();
    }else if(
        hero.x <= (att3.x + 20 || att3.x + 32)
        && att3.x <= (hero.x + 20 || att3.x + 32)
        && hero.y <= (att3.y + 20 || att3.y - 32)
        && att3.y <= (hero.y + 20 || att3.y - 32)
    ){
        end();
    }else if(
        hero.x <= (att4.x + 20 || att4.x + 32)
        && att4.x <= (hero.x + 20 || att4.x + 32)
        && hero.y <= (att4.y + 20 || att4.y - 32)
        && att4.y <= (hero.y + 20 || att4.y - 32)
    ){
        end();
    }

};

2 个答案:

答案 0 :(得分:1)

由于您对每个攻击者都做同样的事情,因此最好制作一个执行该操作的函数,并针对每个攻击者运行它。在这里,我将把所有攻击者放在一个数组中并使用forEach遍历列表。

var attackers = [
    att1, att2, att3, att4, att5
];

function ereset(){
    attackers.forEach(moveAttacker);
}

function moveAttacker(attacker){
    attacker.x = 0 + (Math.random() * (canvas.width - 64));
    attacker.y = -60 ; 
}

答案 1 :(得分:0)

OOP工作:

var Attacker = function() {
    this.x = 0;
    this.y = 0;

    this.init = function(ix, iy) {
      this.x = ix;
      this.y = iy;
    };
};

var ereset = function(){

    this.attackers = 5;
    this.swat = [];

    for ( var n = 0; n < this.attackers; n++ )
    {
         var att = new Attacker();
         att.init(0 + (Math.random() * (canvas.width - 64)), -60 );
         this.swat.push(att);
    }
};

var checkHero = function (hero, attackers)
{
      for ( var n = 0; n < attackers.length; n++  )
      {
         if (
             hero.x <= (attackers[n].x + 20 || attackers[n].x + 32)
             && attackers[n].x <= (hero.x + 20 || attackers[n].x + 32)
             && hero.y <= (att1.y + 20 || attackers[n].y - 32)
             && attackers[n].y <= (hero.y + 20 || attackers[n].y - 32)
            ){
               end();
         }
       }
 };

或类似的东西,这不是经过测试的代码,只是一种方法!