我有一堆不同的npc。它们都有不同的属性和不同的AI,所以我为每个类型创建了一个单独的类,并从一个基类实体派生它。我想让它可以为每种类型的实体分配一个id,这样我就可以直接调用CreateNewEntity(int,Vector2 position)。我该怎么做呢?我也有一种感觉,我的设计很糟糕。这是真的吗
发布于 2011-07-15 13:44:40
有几种方法可以做到这一点。您可以创建一个属性,该属性将为类型提供一些元数据,例如ID。
public class RenderableEntity{
}
[EntityTypeAttribute(Name = "Wizard"]
public class Wizard : RenderableEntity{
}然后,您可以将它们全部捆绑到一个名称空间或逻辑容器中,并按如下方式创建类型:
//Create Entity
//Type Name
string entityName = "Wizard";
//Get the Type
from the namespace where the type has the custom attribute applied to it. Get the type
//Activator.Create(typeof(TheWizardType))另一种方法是,您可以只获取名称与传递给create方法的字符串相匹配的Type。
发布于 2011-07-15 12:18:14
从基本实体继承听起来是一种很好的方法。所有对象之间共享的任何东西都应该在基本实体中,而特定于每种类型的NPC的任何东西都应该在它们自己的类中。具有相同目的但实现不同的东西(如AI或CreateNewEntity)应该标记为虚拟的,因此可以从基本实体列表中调用方法,但正确的实现将会运行。CreateNewEntity可能应该是一个构造函数。
示例:
public class Entity
{
public int Id { get; protected set; }
public Vector2 Position { get; protected set; }
public int Strength { get; protected set; }
public Entity(int id, Vector2 position)
{
Id = id;
Position = position;
Strength = 1;
}
public virtual RunAI()
{
Position.X = Position.X + 1;
}
}
public class SuperHero
{
public SuperHero(int id, Vector2 position) : base (id, position)
{
Strength = 20;
}
public override void RunAI()
{
Position.X = Position.X + 500;
}
}发布于 2011-07-17 22:44:32
听起来像是flyweight模式在这里会很有用:http://www.primos.com.au/primos/Default.aspx?PageContentID=27&tabid=65
您可能希望区分使每个实体不同的核心状态,然后将尽可能多的内容放在共享实例中。
https://stackoverflow.com/questions/6702546
复制相似问题