应用Unity的Dots技术再一个锥形范围内不断生成子弹《一》
创建一个子弹结构体
public struct BulletMove : IComponentData { public float MoveSpeed; public float ExistTime; }
创建子弹移动系统
创建一个子弹生成时间,遍历拥有这些结构体的组件,并操纵这些实体!
private readonly float LifeTime = 5f;
protected override void OnUpdate()
{
Entities.ForEach((Entity e, ref BulletMove bulletMoveSpeed, ref Translation transform, ref LocalToWorld lw) =>
{
transform.Value += (float3)Vector3.Normalize(lw.Forward) * bulletMoveSpeed.MoveSpeed * Time.DeltaTime;
Debug.Log(bulletMoveSpeed.ExistTime + " : bulletMoveSpeed.ExistTime ::");
if(UnityEngine.Time.realtimeSinceStartup - bulletMoveSpeed.ExistTime > LifeTime)
{
EntityManager.DestroyEntity(e);
}
});
}
生成一定数量的实体
public Mesh m_mesh; public Material m_material;//这里写好后记得出去给这两个玩意儿赋值 private void Update() { if (Input.GetMouseButtonDown(0)) { Fire(); } }
private void Fire()
{
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityArchetype archeType = entityManager.CreateArchetype(
typeof(RenderMesh), typeof(Translation), typeof(RenderBounds),
typeof(BulletMove), typeof(LocalToWorld), typeof(Rotation)//typeof(LocalToParent)
);
NativeArray<Entity> entityArray = new NativeArray<Entity>(10000, Allocator.Temp);这里的数量是多少就创建多少个实体!
entityManager.CreateEntity(archeType, entityArray);
for (int i = 0; i < entityArray.Length; i++)
{
entityManager.SetSharedComponentData(entityArray[i], new RenderMesh
{
mesh = m_mesh,
material = m_material
});
entityManager.SetComponentData(entityArray[i], new Rotation
{
Value = quaternion.Euler(0, (float)UnityEngine.Random.Range(-30, 30) / 30, 0)
});
entityManager.SetComponentData(entityArray[i], new Translation
{
Value = new float3(/*UnityEngine.Random.Range(0, 15)*/0, 0, 0)
});
entityManager.SetComponentData(entityArray[i], new BulletMove
{
MoveSpeed = 10f,
ExistTime = (float)Time.realtimeSinceStartup
});
}
entityArray.Dispose();
|