2017-08-11 108 views
0

我使用的代码从这个小提琴多个对象的随机运动:createJS - 集装箱

https://codepen.io/rauluranga/pen/KwoBdE

我想使用此代码,使我enemies.container每个对象都有随机运动。

代码:

if(ticker2 > 80) { 
xT2 = Math.ceil(Math.random()*600) + 100;     
yT2 = Math.ceil(Math.random()*400) + 100; 
ticker2 = 0; 
} 
ticker2++; 

xP2 += (xT2 - xP2)/15; 
yP2 += (yT2 - yP2)/15; 

wingman2.x += ((xP2 - wingman2.x)/60); 
wingman2.y += ((yP2 - wingman2.y)/60); 

我试了一下,到目前为止:

做一个for循环遍历所有的enemies.length并为每个敌人创建一个新的XT和YT号:

if(ticker > 50) { 

xT.length = 0; 
yT.length = 0; 

for(var count = 0; count < enemies.children.length; count++) { 
xT.push(Math.ceil(Math.random()*700) + 100);     
yT.push(Math.ceil(Math.random()*500) + 100); 
} 
ticker = 0; 
} 
ticker++; 

现在,我被困在向前迈进。

for(var count = 0; count < xT.length; count++) { 

xP += (xT[count] - xP)/15; 
yP += (yT[count] - yP)/15; 

} 

for(var count = 0; count < enemies.children.length; count++) { 

enemies.children[count].x += ((xP - enemies.children[count].x)/60); 
enemies.children[count].y += ((yP - enemies.children[count].y)/60); 

} 

我试着做更多的forloops和数组,但零成功。

回答

1

您可以直接将属性添加到敌人对象。这将使一切都变得更容易理解和维护。

function initEnemies(){ 
    for(var count = 0; count < enemies.children.length; count++) { 

     var enemy = enemies.children[count] 

     enemy.targetX = 0 
     enemy.targetX = 0 

     enemy.moveX = 0 
     enemy.moveY = 0 

     enemy.ticker = 0 

    } 
} 

function updateEnemies(){ 
    for(var count = 0; count < enemies.children.length; count++) { 

     var enemy = enemies.children[count] 

     if(enemy.ticker>50){ 

      enemy.targetX = Math.ceil(Math.random()*600) + 100 
      enemy.targetX = Math.ceil(Math.random()*600) + 100 

      enemy.ticker = 0 
     } 
     enemy.ticker++ 

     enemy.moveX += (enemy.targetX - enemy.moveX)/15 
     enemy.moveY += (enemy.targetY - enemy.moveY)/15 

     enemy.x += (enemy.moveX - enemy.x)/60 
     enemy.y += (enemy.moveY - enemy.y)/60 
    } 
}