【发布时间】:2017-08-01 16:47:54
【问题描述】:
我目前正在使用 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 是一个精灵组件列表
任何帮助都会很棒!
【问题讨论】:
-
不清楚您所说的“有时它不能正常工作”是什么意思。忽略应用程序的功能,您是说“obj.AddComponent()”行不会导致将组件添加到组件列表中吗?这似乎不太可能。我认为您更有可能没有正确处理 GDI+ Bitmap 对象,因为这些对象需要仔细的生命周期管理。我们在这里没有完整的代码图片 - 我们看不到 sprs[] 是如何创建的,所以如果我将您的代码示例输入到 VS.net 中,它将无法编译。我们需要一个可验证的示例来提供帮助。
-
如果您阅读我的代码中的 cmets,我会说“这不起作用,只会将一些精灵渲染到屏幕上”。 sprs[] 是 SpriteComponents 的列表,使用 new 关键字 (sprs = new List
();) 创建。精灵组件都被添加到屏幕上,但由于某种原因,当我将 sprs 列表中的精灵组件传递给 AddComponent 方法时,并不是所有的精灵组件都被渲染。 -
-您是说“obj.AddComponent()”行不会导致将组件添加到组件列表中吗?或者只是他们没有正确渲染?
-
@PhillipH obj.AddComponent() 方法确实将一个组件添加到列表中,但是当我写这行“obj.AddComponent(spr[sprID]);”时而不是其他两个选项,不是所有的精灵都渲染到屏幕上。回顾一下,所有组件都被添加到列表中,但当我使用“obj.AddComponent(spr[sprID]);”行时,并非所有组件都呈现到屏幕上
标签: c# game-engine gdi+