When you say Z.y += 1
, you will get an error because Z is the zombie class, not the zombies themselves. The class is the blueprint you use to create zombies, by doing new Z
. new Z
is what actually creates a zombie object, and the zombies objects are what have the y
property, not the Z class. This lets you create multiple zombies, each with their own independent y.
Let's start with just one zombie:
trace("start zombies");
var zombie : Z = new Z();
addChild(zombie);
addEventListener(Event.ENTER_FRAME,zombieMove);
function zombieMove(event:Event) : void
{
zombie.y += 1;
}
Z is the class for a zombie, so I instantiate it by doing new Z
. I store this new zombie object in a variable called zombie
. Then, to move that zombie, I change zombie.y
.
Now how do we move multiple zombies? Well, one way is to add the ENTER_FRAME
listener to the object itself:
function createZombie() : void {
var zombie : Z = new Z();
zombie.x = Math.random() * 400; // randomly position zombie
addChild(zombie);
zombie.addEventListener(Event.ENTER_FRAME,zombieMove);
}
function zombieMove(event:Event) : void
{
// move the zombie that caused this event
event.currentTarget.y += 1;
}
// create two zombies
createZombie();
createZombie();
In this case, we add the ENTER_FRAME
listener to the zombie when we create it. Note that the zombie
variable only exists inside the createZombie
function, so we can't use it in zombieMove
anymore. Besides, which zombie would it refer to? Instead, in the zombieMove
function, we use event.currentTarget
. This is a property of the event
that tells you which object is dispatching the event (a zombie). Since each zombie has its own listener, this function gets called for both zombies.
Another method is to store the zombies in an array:
var zombies : Array = new Array();
function createZombie() : void {
var zombie : Z = new Z();
zombie.x = Math.random() * 400; // randomly position zombie
addChild(zombie);
zombies.push(zombie); // add the zombie onto the list
}
function zombieMove(event:Event) : void
{
// move all of the zombies in the zombies list
for each(var zombie : Zombie in zombies) {
zombie.y += 1;
}
}
addEventListener(Event.ENTER_FRAME, zombieMove);
// create two zombies
createZombie();
createZombie();
In this case, when we create a zombie, we stick it in a list (zombies
). We are back to one ENTER_FRAME
listener, but now this listener will move all of the zombies in the list in one shot.
You also may want to rename your class from Z
to Zombie
. It's a common convention to have classes start with uppercase (Zombie
), with the corresponding objects start with lowercases (zombie
, zombie1
, myZombie
, etc.) This will help clear up your confusion about classes and objects -- the lowercased objects have the properties you want.