At 12/29/21 03:44 PM, Nabella wrote:
Okay, I'm definitely confused by this. I still haven't figured out how classes or for loops work yet, but I bet it'll make life much easier once I do.
Other programmers will hate hearing this but I don't actually use classes. I do use a lot of arrays and for loops, though.
Think of an array as a list if items. You start by creating the list and specifying the max number of items, so it could be:
aEnemies = new Array(20);
or you could do this:
nMaxEnemies = 20;
aEnemies = new Array(nMaxEnemies);
I like to put a character at the start of my variables to specify what sort of variable it us, like an array, number, string, object, movieclip, etc... Makes it easier to know what my code is referring to later.
When you create a new enemy movieclip, you can add that movieclip to the array like this:
aEnemies.push(mEnemy);
Then if you want something like the player's bullet to check all of the enemies:
for (var n=0; n<aEnemies.length; n++){
var mEnemy = aEnemies[n];
// Do your collision check with the enemy here.
}
If your enemy array length is 3, it would end up checking these slots:
aEnemies[0]
aEnemies[1]
aEnemies[2]
That's why you cap the loop at < aEnemies.length and not <= aEnemies.length, because you're including zero in there, so three spaces goes from 0-2.
For removing things from an array, you could make a function like this:
function f_Pop(mClip, aArray){
for (var n in aArray){
if (aArray[n] == mClip){
aArray.splice(n,1);
return;
}
}
}
So you could stuff like
f_Pop(mEnemy, aEnemies);
However you wouldn't want to do that inside the loop I wrote above, because you're changing the array as you're still moving through it. If you want to remove an enemy while inside a loop, you should run it in reverse:
for (var n=aEnemies.length-1; n>=0; n--){
var mEnemy = aEnemies[n];
// Do your collision check with the enemy here.
// Removing enemy from the array here? Do this:
aEnemies.splice(n, 1);
}
This way, you're removing things from back to front... You can also ignore the f_Pop function here since you are already looking at a specific spot in the array here.
I hope I wrote all that correctly!