0
votes
private function onEnemigo(e:TimerEvent):void{

        var tiempoTranscurrido:int = getTimer() - ultimoEnemigo;

        if(tiempoTranscurrido > proximoEnemigo){

            ultimoEnemigo = getTimer();
            var enemigo: int = Math.floor(Math.random() * numeroDeEnemigos);

            this["enemigo"+enemigo+"_act"].play();
            proximoEnemigo = Math.floor(Math.random() * 2000);

            }

        }   

I want to play a random Scene between enemigo0_act and enemigo4_act, considering that numeroDeEnemigos = 4.

Why does "this["enemigo"+enemigo+"_act"]" work? It works how it should but I don't understand why, I mean, what exactly is the function of "this" in this example?

2

2 Answers

0
votes

this is a reserved keyword in as3 that means the instance of the class. In this context, this refers to your MovieClip object (or the MainTimeLine), which happens to have your scenes as properties. You can access the properties of a MovieClip via square brackets and property names. In fact, you can do this with any Object.

0
votes

the reason you require 'this' in your example is to hint Flash to use what's called ARRAY NOTATION to reference your object.

I assume you know that your code is looking for a random "enemigo" movieclip named: "enemigoX_act" where X is your random integer.

Without the 'this' keyword, Flash will attempt to parse ["enemigo"+enemigo+"_act"] as a string, and since strings don't have the play() function, it will return an error.

When you put 'this' in front of the object that you name inside the square brackets, you tell Flash that you are not looking for a string, but you are about to reference an object using array notation.

In summary,

this["enemigo"+ 5 +"_act"]

is the same as directly referencing

enemigo5_act

and

this.enemigo5_act

so as you can see, array notation is useful in your case so that you can call a random enemigo without direct object notation.