我目前正在使用C#中的GDI+开发一个游戏引擎。目前,我正在实现组件。组件可以附加到游戏对象上。游戏对象被渲染到显示在窗口/窗体上的屏幕上。
在我继续之前,先看一下GameObject类中的以下几行:
private List<Component> components = new List<Component>();
public GameObject()
{
AddComponent(new Transform());
}
public void Update(GameTime gameTime)
{
components.ForEach(c => c.OnUpdate(gameTime));
}
public void Render(GraphicsEngine graphicsEngine)
{
components.ForEach(c => c.OnRender(graphicsEngine));
}
public void AddComponent(Component component)
{
component.gameObject = this;
components.Add(component);
}
public T GetComponentOfType<T>() where T : Component
{
return (T)GetComponentOfType(typeof(T));
}
private Component GetComponentOfType(Type type)
{
for (int i = 0; i < components.Count; i++)
if (components[i].GetType() == type)
return components[i];
return null;
}
public Transform Transform
{
get { return GetComponentOfType<Transform>(); }
}现在,希望当我向你展示下一段代码时,事情会变得更清晰一些。
基本上,我有一个从XML文件加载一组游戏对象的方法。但由于某些原因,根据我将精灵组件添加到游戏对象的方式,有时它不能正常工作,并且只有一些精灵渲染到屏幕上
下面是加载游戏对象的方法的部分代码:
// Creates the object and sets the position
GameObject obj = new GameObject();
obj.Transform.Position = new Maths.Vector2(x * map.TileWidth, y * map.TileHeight);
// This works and renders all sprites to the screen
// obj.AddComponent(new SpriteComponent(sprs[sprID].Bitmap));
// This works and renders all sprites to the screen
// obj.AddComponent(new SpriteComponent());
// obj.GetComponentOfType<SpriteComponent>().Bitmap = sprs[sprID].Bitmap;
// This doesn't work and only renders some sprites to the screen
obj.AddComponent(sprs[sprID]);
// Adds the game object to the screen
screen.AddGameObject(obj);为了清楚起见,sprs是sprite组件的列表
任何帮助都是很棒的!
发布于 2017-03-11 23:58:47
好的-最可能的解释是AddComponent在将游戏对象添加到列表之前将它的引用放到了组件中,但我猜您的sprs[]数组构造没有-如果没有所有的代码,就很难判断了。
https://stackoverflow.com/questions/42733660
复制相似问题