You seem to be unsure of how the for
loop works. Recapping:
for ( iniciação ; condição de permanência ; passo ao final ) { corpo }
- initiation: code to be executed before to start the loop. It always runs regardless of whether or not it is satisfied.
- stay condition: test before entering the body. He always tests, even before entering the body for the first time. If the result is
true
, it enters the body, if it is false
it does not enter and it goes to the next instruction (i.e. that after for
).
- body: code that is executed multiple times, until the persistence condition becomes
false
or that exits abruptly through break
, return
or in case of exception.
- step to the end: then code of the body. If the body finishes normally, or if the
continue
statement is used, this step will be executed shortly thereafter. It occurs before from the permanence condition being tested again.
Looking at your code, I think your intent is to go through the entire list of objects, right? This way, your target must follow from the first index in the list to the last one. As you already know, ActionScript, indexing starts from zero, so the first index (initialization) is correct. The step is also correct (increment one in the index) and the final index ( lastEnemy
) too - since it is the list size minus one. The problem is in the staying condition, then.
As summarized in the @ramaral response , your staying condition ( alvo >= lastEnemy
) is false even before of starting the loop (since the list of objects is greater than zero, config tested by its if
- otherwise you would have an infinite loop). This leads me to believe that you were trying to create a stop condition instead, am I right? Anyway, this stopping condition would not be correct, since it would exit as soon as alvo
was equal to lastEnemy
(and you want it to quit soon after it). That is, stop if alvo > lastEnemy
.
The solution is then to deny the stop condition [corrected], to obtain the stay condition. !(alvo > lastEnemy)
which is equivalent to alvo <= lastEnemy
. That way, it will continue in the loop while alvo
is less than or equal to lastEnemy
, and exit as soon as this condition becomes false.