Arsenil98
Arsenil98

Reputation: 16

AS3 - Array called into a new function... HOW?

Sup everyone, well since my last post as been super fast to fix due to my tired eyes. I'm gonna ask you one more favor...

It's about an Array, so before i had only one "target" showing. So i thought my game was way to simple...

So i decided to add more target that moves, and place with random math... Well they are correctly placed, but only one is moving. I think is the first one that is being created....

This is my line of code :

// Creating multiple targetwith ADDCHILD and ARRAY at different location //

var arraymc_target:Array = [];
for(var i:int = 1; i<8; i++)
{
    var mc_target:target = new target();
    mc_target.x = Math.floor(Math.random() * 400);
    mc_target.y = Math.floor(Math.random() * 550);
	addChild(mc_target);
    arraymc_target.push(mc_target);
}

// Creating the TARGETS MOVEMENT  //
function goesside_1(event:Event):void {
	mc_target.x -= 2;
		if (mc_target.x < -20){
		mc_target.x = 550;
}
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);

// ----------------------------------------------- //

Upvotes: 0

Views: 35

Answers (1)

Marcela
Marcela

Reputation: 3728

Your main issue is that in goesside_1, you're moving mc_target which is simply a reference to the last instance of target you created in the loop and pushed to the array.

Another quirk I noticed is that you're adding the ENTER_FRAME listener to one of your targets instead of to the stage.

What you want to do is add the listener to the stage, and then loop over each of the targets in your array:

var arraymc_target:Array = [];
for(var i:int = 1; i<8; i++)
{
    var mc_target:target = new target();
    mc_target.x = Math.floor(Math.random() * 400);
    mc_target.y = Math.floor(Math.random() * 550);
    addChild(mc_target);
    arraymc_target.push(mc_target);
}

// Creating the TARGETS MOVEMENT  //
function goesside_1(event:Event):void {
    for each(var mc_target:target in arraymc_target)
    {
        mc_target.x -= 2;
        if (mc_target.x < -20){
            mc_target.x = 550;
        }
    }
}

stage.addEventListener(Event.ENTER_FRAME, goesside_1);

Upvotes: 1

Related Questions