我是直接在git上下载的ecs包:官方ECS的Git库。
ECS主要用三个类来控制:
这个类应该直接绑定在我们的物体上:
public class MoveAuthor : MonoBehaviour
{
class Baker : Baker<MoveAuthor>
{
public override void Bake(MoveAuthor authoring)
{
var entity = GetEntity(TransformUsageFlags.Dynamic);
AddComponent<Move>(entity);
}
}
}
其中的Move即为一个继承了IComponentData的接口:
public struct Move : IComponentData
{
}
最后是system:
public partial struct MovingSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
//这里先请求update绑定的move结构体
state.RequireForUpdate<Move>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var dt = SystemAPI.Time.DeltaTime;
foreach (var (transform, entity) in
SystemAPI.Query<RefRW<LocalTransform>>()
.WithAll<Move>()
.WithEntityAccess())
{
// ValueRW returns a ref to the actual component value.
// Add a rotation around the parent's Y axis.
var pos = transform.ValueRO.Position;
// This does not modify the actual position of the tank, only the point at
// which we sample the 3D noise function. This way, every tank is using a
// different slice and will move along its own different random flow field.
pos.y = (float)entity.Index;
var angle = (0.5f + noise.cnoise(pos / 10f)) * 4.0f * math.PI;
var dir = float3.zero;
math.sincos(angle, out dir.x, out dir.z);
transform.ValueRW.Position += dir * dt * 5.0f;
transform.ValueRW.Rotation = quaternion.RotateY(angle);
}
}
}
注意:绑定了MoveAuthor 的物体一定要放在Sub Sence下,不然MovingSystem 的update无法正常运行。
在MoveAuthor中,GetEntity(TransformUsageFlags.Dynamic)是需要Dynamic的,最开始我是使用的TransformUsageFlags.None,会导致物体无法正常移动。