开发者

ID based NPC system

开发者 https://www.devze.com 2023-03-20 16:58 出处:网络
I have a bunch of开发者_C百科 different npcs. They all have different properties and different AI, so I have made a separate class for each type, and derive it from a base class Entity. I want to make

I have a bunch of开发者_C百科 different npcs. They all have different properties and different AI, so I have made a separate class for each type, and derive it from a base class Entity. I want to make it so that I can assign an ID to each type of Entity, so I can just call CreateNewEntity(int id, Vector2 position). How would I do this? I also have a feeling that I'm designing this badly. Is that true


There are a couple of ways you could do this. You could create an Attribute that will give the type some metadata such as ID e.g.

public class RenderableEntity{
}

[EntityTypeAttribute(Name = "Wizard"]
public class Wizard : RenderableEntity{
}

you could then bundle them all in a namespace or a logical container and create the type as follows pseudo:

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

The other is that you could just get the Type where the name matches the string you passed into your create method.


Inheriting from a base entity sounds like a good approach. Anything that is shared between all your objects should be in the base entity, and anything that is specific to each type of NPC, should be in their own class. Things that have the same purpose, but different implementation (like AI, or CreateNewEntity) should be marked virtual, so the methods can be called from a list of base entities, but the correct implementation will run. CreateNewEntity should probably be a constructor.

example:

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


It sounds like the flyweight pattern would be beneficial here: http://www.primos.com.au/primos/Default.aspx?PageContentID=27&tabid=65

You probably want to differentiate the core state that makes each entity different and then put as much as possible in the shared instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消