我正在使用这个小提琴的代码:
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和数组,但没有成功。
答案 0 :(得分: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
}
}