在使用XNA在C#中完成基于组件的游戏引擎之前,我认为这是最后一次大的逻辑飞跃.我定义了我的Entity类和抽象组件.我的问题出现在我的EntityFactory中.
当我想创建一个新实体时,我将一个EntityType枚举传递给工厂中的静态方法,并通过一个switch/case语句查找要组合在一起的组件.问题是,我正在尝试创建一种方法,组件可以与同一实体中的其他组件共享字段,而无需访问所有内容.例如,如果两个组件具有表示位置的Vector2字段,则它们都应指向相同的Vector2.
我可以通过初始化实体工厂中的所有字段并要求将它们传递到组件的构造函数(并使用ref作为基元)来实现这一点,但这将非常难以维护,因为任何时候我扩展或更改了组件,我将不得不在工厂中的每个使用组件的地方重写代码.我真的想避免这种解决方案,但如果我找不到更好的方法,我会忍受它.
我目前的解决方案是创建一个名为Attribute的包装类.它包含两个字段:
private AttributeType type;
private Object data;
Run Code Online (Sandbox Code Playgroud)
属性类型是枚举,表示属性的用途.所以在位置,旋转,纹理等枚举中有条目.
EntityFactory创建一个空的属性列表,并将其传递给每个组件构造函数.setField方法将由组件的构造函数调用,而不是初始化字段.这是Attribute类和setField方法.
public class Attribute
{
private AttributeType type;
private Object data;
public AttributeType Type
{
get { return this.type; }
}
public Object Data
{
get { return this.data; }
}
public Attribute(AttributeType type, Object data)
{
this.type = type;
this.data = data;
}
public static void setField<T>(List<Attribute> attributeList, AttributeType type, out T field, T defaultValue)
{
bool attributeFound = false;
field = defaultValue;
foreach (Attribute attribute in attributeList) …Run Code Online (Sandbox Code Playgroud) 我正在开发 XNA 游戏。这是我对架构小心翼翼的时候了。直到今天,我一直以这种方式实现我自己的绘制方法:
public void Draw(SpriteBatch sb, GameTime gameTime)
{
sb.Begin();
// ... to draw ...
sb.End();
}
Run Code Online (Sandbox Code Playgroud)
我正在挖掘 DrawableGameComponent 并看到 Draw 方法是这样来的:
public void Draw(GameTime gameTime)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
首先,我知道SpriteBatch 可以在Begin 和End 之间收集许多Texture2D,以便对它们进行排序或使用相同的Effect 进行绘制很有用。
我的问题是关于通过 SpriteBatch 的性能和成本。在 DrawableGameComponent 中,如果 spritebatch 是公开的,则可以调用游戏对象的 spritebatch。
有什么建议,xna-game 程序员应该做什么?
谢谢指教。
它在"Game1.cs"中增长了太多纹理/向量.Draw和Update也更大,不易管理.你们这样做的?
嗨,我是xna的新手,我正在尝试制作一个简单的游戏,你的小船可以四处移动,避免从顶部到底部坠落的小行星.我有船移动和一颗小行星坠落,但我不知道如何让大量的小行星从相同的纹理中掉落,以及如何让它们每隔一段时间掉落一次.到目前为止这是我的小行星类:
namespace Asteroids
{
class Asteroids
{
Texture2D AsteroidTexture;
Vector2 Position;
Random random = new Random();
float AsteroidSpeed = 5;
public void Initialize()
{
Position.Y = 0;
Position.X = random.Next(0, 1000);
}
public void Update()
{
Position.Y += AsteroidSpeed;
if (Position.Y > 600)
{
Position.Y = 0;
Position.X = random.Next(0, 1000);
}
}
public void Load_Content(ContentManager Content)
{
AsteroidTexture = Content.Load<Texture2D>("asteroid");
}
public void Draw(SpriteBatch SpriteBatch)
{
SpriteBatch.Draw(AsteroidTexture, Position, Color.White);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Game1课程:
namespace Asteroids
{
public class Game1 …Run Code Online (Sandbox Code Playgroud)