S.A.Parkhid S.A.Parkhid - 3 months ago 29
ActionScript Question

Spawn Enemies in ActionScript 3.0

Something is going wrong in my mind, In my game , I want to instantiate enemies within library and put them on stage. so I create an EnemySpawner class and I put an instance from that class onto the stage . ( drag drop from library and give it a instance name). So here is the code for EnemySpawner class:

package scripts {
import flash.display.MovieClip;

public class EnemySpawner extends MovieClip {

var positions: Array = new Array(); // clockwise spawn positions
var enemies : Array = new Array();
var spwan:Boolean=false;
public function EnemySpawner() {
enemies.push("Enemy1");// here is the problem

public function tick(): void {

public function doSpwan():void{




So the problem issues here is , I want to randomly load enemies from library and instance them on stage , the design environment is something like this :

There are diffrent enemy movieclips in library with same blass class:

pic from  lib

I don't want to assign each enemy a new class , for example I don't want to assign EnemyA Class to Enemy1 MovieClip Object and EnemyB Class to Enemy2 MovieClip . I want All Enemy MovieClip in the library share same class Enemy. so but using this , instantiate is hard task, I don't know how to instantiate enemies by using this method?

I know if I have separate class for each Enemy I can do this:

var e1 : Enemy1 = new Enemy1();
var e2 : Enemy2 = new Enemy2();

var e3 : Enemy3 = new Enemy3();

But I want do something like this:

//Instantiate form library (Name Of Enemy1); //base class is enemy 1
//Instantiate form library (Name Of Enemy1); //base class is enemy 1
//Instantiate form library (Name Of Enemy1); //base class is enemy 1

Thanks in advance.

Answer Source

It's an easy task, actually. Assign enemies with different classes, then

// List classes in this Array.
var Enemies:Array = [Enemy1, Enemy2, Enemy3];

// Get a random class from the list.
var anIndex:int = Math.random() * Enemies.length;
var EnemyClass:Class = Enemies[anIndex];

// Spawn a random enemy.
// You can have a common superclass, or just use MovieClip or Sprite they are subclassed from.
var anEnemy:MovieClip = new EnemyClass;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download