版本:unity 5.6 语言:C#
总起:
今天主要承接上一节的内容来实现点击右键创建角色、点击左键移动角色的功能。
这边会在IComponent中保存Unity场景中GameObject的引用,以便在各个System中使用,并使用Link方法可以在场景中的看到调试信息。
如果你第一次学习该内容,请根据第二节内容完成input相关的代码(主要EmitInputSystem)。这里我提供一下已经完成的工程:Entitas简单移动项目。
GameComponents:
这边提供了所有后面要用到的Components,直接看代码吧:
// GameComponents.cs
using UnityEngine;
using Entitas;
// 当前GameObject所在的位置
[Game]
public sealed class PositionComponent : IComponent
{
public Vector2 value;
}
// 当前GameObject朝向
[Game]
public class DirectionComponent : IComponent
{
public float value;
}
// GameObject显示的图片
[Game]
public class ViewComponent : IComponent
{
public GameObject gameObject;
}
// 显示图片的名称
[Game]
public class SpriteComponent : IComponent
{
public string name;
}
// GameObject是否是Mover的标志
[Game]
public class MoverComponent : IComponent
{
}
// 移动的目标
[Game]
public class MoveComponent : IComponent
{
public Vector2 target;
}
// 移动完成标志
[Game]
public class MoveCompleteComponent : IComponent
{
}
Component的数量有点多,这边要注意自己在写的时候,尽量将Component分的细一些,一个功能对应一个Component,这样在写System的时候会很舒服,自然而然就出来了。
以上的代码写完之后,按住Ctrl + Shift,再按一下G,生成Component对应的Entitas代码。
点击右键产生一个移动者:
首先我们需要在检测到InputContext有右键按下时,就在GameContext中生成一个代表移动者的GameEntity:
// CreateMoverSystem.cs
using System.Collections.Generic;
using Entitas;
using UnityEngine;
// 监听的是InputContext中的右键数据,所以是InputEntity的ReactiveSystem
public class CreateMoverSystem : ReactiveSystem<InputEntity>
{
readonly GameContext _gameContext;
public CreateMoverSystem(Contexts contexts) : base(contexts.input)
{
_gameContext = contexts.game;
}
// 收集有RightMouse和MouseDown的InputEntity
protected override ICollector<InputEntity> GetTrigger(IContext<InputEntity> context)
{
return context.CreateCollector(InputMatcher.AllOf(InputMatcher.RightMouse, InputMatcher.MouseDown));
}
// 第二过滤,直接返回true也无所谓
protected override bool Filter(InputEntity entity)
{
return entity.hasMouseDown;
}
// 执行,每次按下右键,设置Mover标志,添加Position、Direction,并添加表现该Entity的图片名称
protected override void Execute(List<InputEntity> entities)
{
foreach (InputEntity e in entities)