0

I've been working on a simple game in AS3, but I can't seem to add in movement for the different types of enemies. So far it only works for 1 enemy type:

enemyType1 is the enemy movieclip.

var enemyType1:EnemyType1 = new EnemyType1(0, 0);
var enemies:Array = new Array();

And in my game loop, I randomly spawn the enemies and have a for loop, which loops through all the enemies, and performs the movement for each enemy.

if(Math.random() < 0.5)
{
    var newEnemyType1 = new EnemyType1(0, 0);
    enemies.push(newEnemyType1);
    addChild(newEnemyType1);
}

for (var i:int = 0; i < enemies.length; i++)
{
    //Movement
}

The problem comes when creating different types of enemies and determining which enemy type the enemy is, so that the correct type of movement will be used. This becomes:

var enemyType1:EnemyType1 = new EnemyType1(0, 0);
var enemyType2:EnemyType2 = new EnemyType2(0, 0);
var enemies:Array = new Array();

And in the game loop:

if(Math.random() < 0.5)
{
    var newEnemyType1 = new EnemyType1(0, 0);
    enemies.push(newEnemyType1);
    addChild(newEnemyType1);
    var newEnemyType2 = new EnemyType2(0, 0);
    enemies.push(newEnemyType2);
    addChild(newEnemyType2);
}

for (var i:int = 0; i < enemies.length; i++)
{
    if(enemies[i] == EnemyType1)
    {
        //EnemyType1 Movement
    }
    else if(enemies[i] == EnemyType2)
    {
        //EnemyType2 Movement
    }
}

Except it doesn't work. I can't recognize enemies[i] for being an object. I have also looked at multidimensional arrays for each enemy type, but couldn't get it to work.

So the question is, how can I detect for a specific object in an array? Or is this completely the wrong way to go about controlling multiple enemy types?

Thanks.

4

3 回答 3

0

尝试使用抽象类和继承:

// Abstract enemy class
public class AEnemy()
{
    public function Move():void
    {
        // standard move code here
    }
}

// Concrete enemy class. Inherits Move code
public class EnemyOne() extends AEnemy
{

}

// Concrete enemy class two, overrides inherited movement code with it's own.
public class EnemyTwo() extends AEnemy
{
    override public function Move():void
    {
        // Different move code here
    }
}

/* ---- In controller ---- */

// typed array of enemies, can contain anything that extends AEnemy.
// Will also see them only as an 'AEnemy'
private var _enemies:Vector.<AEnemy> = new Vector.<AEnemy>();

// update loop
for (i = 0; i < l; i++)
{
    // Move code is handled internally by the enemy classes themselves
    _enemies[i].Move();
}
于 2013-08-22T19:48:07.973 回答
0

这是一个非常简单的任务,只需创建一个超类 Enemy,Enemy1 和其他敌人类扩展即可。

在 Enemy 类中,您可以创建一个 move() 方法,您可以在循环中调用该方法。

于 2013-08-22T03:10:07.293 回答
0

如果要比较类类型,请不要使用“==”,而是使用“is”。
可能它会起作用。

if(enemies[i] is EnemyType1)
{
    //EnemyType1 Movement
}
else if(enemies[i] is EnemyType2)
{
    //EnemyType2 Movement
}
于 2013-08-22T02:50:57.453 回答