1. 起源 Entitas 基本认识

这几天打算跟朋友做一个三消类的游戏,我们计划用Unity 开发 C# + XLua,在网上找了一天的好的框架 看了ET 等,总感觉不太顺手,打算从0开始自己搞一套基于ECS的游戏框架,ECS 基于 Entitas https://github.com/sschmid/Entitas-CSharp.git
ECS 是 Entity Component System 的简称

1. Entitas.IComponent, 我们的组件要继承这个类, 组件只用于存储数据

2. Systems

  •  ReactiveSystem 反应系统,下面是官方解释,在有数据变化时会触发,我们需要重写 触发器,筛选器,执行
/// A ReactiveSystem calls Execute(entities) if there were changes based on
/// the specified Collector and will only pass in changed entities.
/// A common use-case is to react to changes, e.g. a change of the position
/// of an entity to update the gameObject.transform.position
/// of the related gameObject.
public class LogSystem : ReactiveSystem<GameEntity>
{
    public LogSystem(Contexts contexts) : base(contexts.game)
    {
    }
    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        return context.CreateCollector(GameMatcher.HelloWordLog);
    }
    protected override bool Filter(GameEntity entity)
    {
        return entity.hasHelloWordLog;
    }
    protected override void Execute(List<GameEntity> entities)
    {
         foreach (var entity in entities)
         {
             Debug.Log(entity.helloWordLog.message);
         }
     }
}
  • IInitializeSystem 初始化系统 会执行一次初始化操作 例如我们初始化的时候创建了一个Entity,挂在上HelloWordLog组件,这个时候我们的创建的 ReactiveSystem 就会 调用收集,然后执行,这时候就打印出了 entity的 log组件上的 message
    public class InitSystem : IInitializeSystem
    {
        private GameContext _gameContext;
    
        public InitSystem(Contexts contexts)
        {
            _gameContext = contexts.game;
        }
        
        public void Initialize()
        {
            _gameContext.CreateEntity().AddHelloWordLog("HelloWord");
        }
    }

     

  • Feature 特性, 将不同的System添加到Feature以组成新的特性
    public class AddGameSystem : Feature
    {
        public AddGameSystem(Contexts contexts) : base("AddHelloWordSystem")
        {
            Add(new LogSystem(contexts));
            Add(new InitSystem(contexts));
        }
    }

     

  • Entitas的启动 我们创建新的特性,然后初始化这时候会调用到上面定义的IInitializeSystem 系统 
    public class GameController : MonoBehaviour
    {
        public Systems _systems;
        // Start is called before the first frame update
        void Start()
        {
            var context = Contexts.sharedInstance;
            _systems = new Feature("Systems").Add(new AddGameSystem(context));
            _systems.Initialize();
        }
    
        // Update is called once per frame
        void Update()
        {
            _systems.Execute();
            _systems.Cleanup();
        }
    }

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章