2012-01-09 167 views
1

G'day全部,创建一个游戏对象数组

如果我在屏幕上有一些对象称为敌人,我怎么能把它们放入一个数组? 我最初的想法是在创建它时创建它。我把一个声明,我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

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

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); 

因为否则你正尝试将类添加到阵列而不是类:)

+0

谢谢你。这正是我想要的。助教。 – 2012-01-13 12:29:19

2

假设你已经把线public enemy[] enemiesArray = new enemy[5]; 你的游戏类中的实例,那么你的enemiesArray只是你的游戏场类别不是游戏组件,您应该能够将其引用为

myGameClass.enemiesArray[1] 

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

也作为@匿名说,列表比在数组运行时更容易调整大小,因此请考虑使用'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(); 
+0

这是一个很好的下一步,我打算尝试继承过程。助教。 – 2012-01-13 12:30:17

+0

你应该尽早做,而不是晚些时候,可以是一个猪改造这个东西,祝你好运的游戏,虽然:) – Stuart 2012-01-13 17:48:39

相关问题