I am using the code from this fiddle:
https://codepen.io/rauluranga/pen/KwoBdE
I would like to use this code to make each object in my enemies.container have random movement.
Code:
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);
What I tried so far:
making a for loop to loop over the enemies.length and create a new xT and yT numbers for each enemy:
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++;
Now after that I got stuck on moving forward.
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);
}
I tried making more forloops and array but with zero succes.
You can add the properties directly to the enemies objects. This will make everything alot easier to understand and maintain.
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
}
}