problem: ENTER_FRAME event works only on one object

Hi, i’m trying to make the circles i have in my game move around, each one in different direction, but the ENTER_FRAME works only on one circle…

can you help me understand why the loop doesn’t work properly and only one circle is moving around?
thanks :slight_smile:

var xDirection: String = “right”;
var yDirection: String = “down”;
var speed: Number;

for (var i: Number = 0; i < 10; i++) {
var badGuy1: badGuy = new badGuy();
badGuy1.x = GetRandomXPosition();
badGuy1.y = GetRandomYPosition();
/speed = Math.round(.5 + Math.random() * 5);/
addChild(badGuy1);
addEventListener(Event.ENTER_FRAME, MoveBadGuys);
}

// Good guy definition---------------------------------------

var goodGuy1: goodGuy = new goodGuy();
goodGuy1.addEventListener(Event.ENTER_FRAME, goodGuyMovement);
this.addChild(goodGuy1);

function goodGuyMovement(event: Event): void {
Mouse.hide();
goodGuy1.x = mouseX;
goodGuy1.y = mouseY;
}

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

function GetRandomXPosition(): Number {
return Math.floor(Math.random() * stage.stageWidth);
}

function GetRandomYPosition(): Number {
return Math.floor(Math.random() * stage.stageHeight);
}

addEventListener(Event.ENTER_FRAME, MoveBadGuys);
function MoveBadGuys(event: Event): void {
if (badGuy1.x > stage.stageWidth) {
xDirection = “left”;
} else if (badGuy1.x < 0) {
xDirection = “right”;
}

if (badGuy1.y > stage.stageHeight) {
	yDirection = "up";
} else if (badGuy1.y < 0) {
	yDirection = "down";
}


if (xDirection == "right") {
	badGuy1.x += 20;
} else {
	badGuy1.x -= 20;
}

if (yDirection == "up") {
	badGuy1.y -= 20;
} else {
	badGuy1.y += 20;
}

}

Your listener only references badGuy1, which will point to the last instance of badGuy created in the loop. Probably the best solution, at least in my opinion, would be to incorporate the movement code into the badGuy class. Alternatively, you could store all of the badGuys in an array and loop through them all in the enterFrame listener.

thank you :smile:

You’re welcome.