创建一个游戏对象数组

时间:2012-01-09 04:21:06

标签: xna-4.0

G'day All,

如果屏幕上有多个被称为敌人的物体,我该如何将它们放入阵列? 我最初的想法是在它们被创建时这样做。我在Game.cs文件的顶部放了一个声明:

public enemy[] enemiesArray = new enemy[5];

然后当我创建敌人时,我试图将它们添加到数组中:

for (int i = 0; i < 2; ++i) // This will create 2 sprites
        {
            Vector2 position = new Vector2((i+1) * 300, (i+1) * 200);
            Vector2 direction = new Vector2(10, 10);
            float velocity = 10;
            int ID = i;

            Components.Add(new skull(this, position, direction, velocity, ID));
            skullsArray[i] = skull; // This line is wrong
        }

我还尝试使用以下代码在update()方法中使用它:

foreach (GameComponent component1 in Components)
        {
            int index = component1.ID;
            if (component1.ToString() == "enemy")
            {
                enemiesArray[index] = component1
            }
         }

但是这会因为component1没有ID而失败。我必须假设,当程序枚举通过每个GameComponent时,它只能访问该组件的有限范围的数据。

最后我希望能够将敌人称为敌人[1],敌人[2]等。

谢谢, 安德鲁。

2 个答案:

答案 0 :(得分:2)

我不明白为什么你不能使用像数组一样工作的List,但它有一个可变长度。然后你可以这样做:

List<Enemy> EnemyList;

//You have to initalize it somewhere in Initalize or LoadContent (or the constructor)

您可以像添加组件一样添加敌人(因为组件是List<GameComponent>

EnemyList.Add(enemy);

然后你可以访问敌人:

EnemyList[index].DoSomething();
编辑:再次看了你的代码,我注意到头骨不存在。你的意思是

new skull(this, position, direction, velocity, ID);

因为否则你试图将类添加到数组而不是类的实例:)

答案 1 :(得分:2)

假设您已将行public enemy[] enemiesArray = new enemy[5]; 放入游戏类中,那么您的enemiesArray只是游戏类的一个字段而不是游戏组件,您应该可以将其引用为

myGameClass.enemiesArray[1]

假设您的游戏类在范围内。

同样@annonymously说列表在运行时比数组更容易调整大小所以考虑使用'List(5)enemiesArray;'代替

这不是一种非常可扩展的处理方式,所以我建议你研究如何创建和注册GameComponents。也考虑使它成为通用的,这样你就可以有一个地方来引用你所有的游戏物品,而不是拥有enemiesArray,bulletsArray,someOtherArray等等

一种简单的方法是拥有一个像

这样的抽象类
public abstract class GameThing
{
     public Vector2 Position {get; set;}
     //some other props...
}

然后将其用作游戏物品的基础,以便将敌人定义为

public class Enemy : GameThing
{
    //some props
}

而不是 public enemy[] enemiesArray = new enemy[5]; 你会用的 public GameThing[] gameItemsArray= new GameThing[5]; 添加像这样的项目

gameItemsArray[1] = new Enemy();