Exemplo n.º 1
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var query           = GetEntityQuery(typeof(Tag_Ennemy), ComponentType.ReadOnly <Position>());
            var targetEntities  = query.ToEntityArray(Allocator.TempJob);
            var targetPositions = query.ToComponentDataArray <Position>(Allocator.TempJob);

            var targets = new NativeArray <EntityWithPosition>(targetEntities.Length, Allocator.TempJob);

            for (var i = 0; i < targetEntities.Length; i++)
            {
                targets[i] = new EntityWithPosition()
                {
                    entity   = targetEntities[i],
                    position = targetPositions[i].Value
                };
            }

            targetEntities.Dispose();
            targetPositions.Dispose();

            var job = new SetTargetJob
            {
                targets = targets,
                ecb     = endSimulationEcbSystem.CreateCommandBuffer().ToConcurrent()
            };

            var handle = job.Schedule(this, inputDeps);

            endSimulationEcbSystem.AddJobHandleForProducer(handle);

            return(handle);
        }
Exemplo n.º 2
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        Vector3 tempTarget = new Vector3(0, 0, 0);

        EntityQuery                      targetQuery            = GetEntityQuery(typeof(Skeleton), ComponentType.ReadOnly <Translation>());
        NativeArray <Entity>             targetEntityArray      = targetQuery.ToEntityArray(Allocator.TempJob);
        NativeArray <Translation>        targetTranslationArray = targetQuery.ToComponentDataArray <Translation>(Allocator.TempJob);
        NativeArray <EntityWithPosition> targetArray            = new NativeArray <EntityWithPosition>(targetEntityArray.Length, Allocator.TempJob);

        tempTarget = leader.transform.position;

        for (int i = 0; i < targetEntityArray.Length; i++)
        {
            targetArray[i] = new EntityWithPosition
            {
                entity   = targetEntityArray[i],
                position = targetTranslationArray[i].Value
            };
        }
        targetEntityArray.Dispose();
        targetTranslationArray.Dispose();

        UnitHandlerJob unitHandlerJob = new UnitHandlerJob
        {
            targetArray  = targetArray,
            tempTarget   = tempTarget,
            leaderMoving = leader.moving,
        };

        JobHandle jobHandle = unitHandlerJob.Schedule(this, inputDeps);

        return(jobHandle);
    }
Exemplo n.º 3
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            // 查询目标entities
            EntityQuery               targetQuery            = GetEntityQuery(typeof(Target), ComponentType.ReadOnly <Translation>());
            NativeArray <Entity>      targetEntityArray      = targetQuery.ToEntityArray(Allocator.TempJob);
            NativeArray <Translation> targetTranslationArray = targetQuery.ToComponentDataArray <Translation>(Allocator.TempJob);

            // 构造job参数
            NativeArray <EntityWithPosition> args = new NativeArray <EntityWithPosition>(targetEntityArray.Length, Allocator.TempJob);

            for (int i = 0; i < args.Length; ++i)
            {
                args[i] = new EntityWithPosition()
                {
                    entity   = targetEntityArray[i],
                    position = targetTranslationArray[i].Value,
                };
            }

            // 释放临时NativeArray
            targetEntityArray.Dispose();
            targetTranslationArray.Dispose();

            // 生成一个Job,然后调用
            FindTargetJob job = new FindTargetJob()
            {
                targets = args,
                ecb     = endSimulationECBS.CreateCommandBuffer().ToConcurrent(),
            };

            JobHandle handle = job.Schedule(this, inputDeps);

            endSimulationECBS.AddJobHandleForProducer(handle);
            return(handle);
        }
Exemplo n.º 4
0
        public void Execute(Entity entity, int index, ref Translation translation)
        {
            float3 unitPos             = translation.Value;
            Entity closestTargetEntity = Entity.Null;
            float3 closestTargetPos    = float3.zero;

            for (int i = 0; i < targetArray.Length; i++)
            {
                EntityWithPosition targetEntityWithPosition = targetArray[i];
                if (closestTargetEntity == Entity.Null)
                {
                    closestTargetEntity = targetEntityWithPosition.entity;
                    closestTargetPos    = targetEntityWithPosition.position;
                }
                else
                {
                    if (math.distance(unitPos, targetEntityWithPosition.position) <
                        math.distance(unitPos, closestTargetPos))
                    {
                        closestTargetEntity = targetEntityWithPosition.entity;
                        closestTargetPos    = targetEntityWithPosition.position;
                    }
                }
            }

            if (closestTargetEntity != Entity.Null)
            {
                entityCommandBuffer.AddComponent(index, entity, new HasTarget {
                    targetEntity = closestTargetEntity
                });
            }
        }
Exemplo n.º 5
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityQuery                      targetQuery            = GetEntityQuery(typeof(EnemyTag), ComponentType.ReadOnly <Translation>());
        NativeArray <Entity>             targetEntityArray      = targetQuery.ToEntityArray(Allocator.TempJob);
        NativeArray <Translation>        targetTranslationArray = targetQuery.ToComponentDataArray <Translation>(Allocator.TempJob);
        NativeArray <EntityWithPosition> targetArray            = new NativeArray <EntityWithPosition>(targetEntityArray.Length, Allocator.TempJob);

        for (int i = 0; i < targetEntityArray.Length; i++)
        {
            targetArray[i] = new EntityWithPosition
            {
                entity   = targetEntityArray[i],
                position = targetTranslationArray[i].Value,
            };
        }

        targetEntityArray.Dispose();
        targetTranslationArray.Dispose();

        FindTargetJob findTargetJob = new FindTargetJob
        {
            targetArray         = targetArray,
            entityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
        };

        JobHandle jobHandle = findTargetJob.Schedule(this, inputDeps);

        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);

        return(jobHandle);
    }
Exemplo n.º 6
0
        public void Execute(Entity entity, int index, [ReadOnly] ref Translation translation)
        {
            float3 unitPosition          = translation.Value;
            Entity closestTargetEntity   = Entity.Null;
            float3 closestTargetPosition = float3.zero;

            for (int i = 0; i < targetArray.Length; i++)
            {
                EntityWithPosition entityWithPos = targetArray[i];

                if (closestTargetEntity == Entity.Null)
                {
                    // No target
                    closestTargetEntity   = entityWithPos.entity;
                    closestTargetPosition = entityWithPos.position;
                }
                else
                {
                    if (math.distance(unitPosition, entityWithPos.position) < math.distance(unitPosition, closestTargetPosition))
                    {
                        // This target is closer
                        closestTargetEntity   = entityWithPos.entity;
                        closestTargetPosition = entityWithPos.position;
                    }
                }
            }

            closestTargets[index] = closestTargetEntity;
        }
Exemplo n.º 7
0
 public void Execute(Entity entity, int index, ref Translation translation)
 {
     targetArray[index] = new EntityWithPosition
     {
         entity   = entity,
         position = translation.Value
     };
 }
    // protected override JobHandle OnUpdate(JobHandle inputDeps) {
    protected override void OnUpdate()
    {
        //set the query for temp and translation
        // EntityQuery targetQuery = GetEntityQuery(typeof(Temperature), ComponentType.ReadOnly<Translation>());

        //convert to native arrays of entities and components
        NativeArray <Entity>      targetEntityArray      = targetQuery.ToEntityArray(Allocator.TempJob);
        NativeArray <Translation> targetTranslationArray = targetQuery.ToComponentDataArray <Translation>(Allocator.TempJob);
        NativeArray <Temperature> targetTemperatureArray = targetQuery.ToComponentDataArray <Temperature>(Allocator.TempJob);

        //allocate a EntityWithPosition struct array
        NativeArray <EntityWithPosition> targetArray = new NativeArray <EntityWithPosition>(targetEntityArray.Length, Allocator.TempJob);

        //fill struct array
        for (int i = 0; i < targetEntityArray.Length; i++)
        {
            targetArray[i] = new EntityWithPosition {
                entity      = targetEntityArray[i],
                position    = targetTranslationArray[i].Value,
                temperature = targetTemperatureArray[i].Value
            };
        }

        //clean up
        targetEntityArray.Dispose();
        targetTranslationArray.Dispose();
        targetTemperatureArray.Dispose();

        // EntityQuery unitQuery = GetEntityQuery(typeof(Unit), ComponentType.Exclude<HasTarget>());
        // NativeArray<Entity> closestTargetEntityArray = new NativeArray<Entity>(unitQuery.CalculateLength(), Allocator.TempJob);

        //do work son
        FindTargetBurstJob findTargetBurstJob = new FindTargetBurstJob {
            targetArray     = targetArray,
            deltaTime       = .01f,
            TranslationType = GetComponentTypeHandle <Translation>(true),
            TemperatureType = GetComponentTypeHandle <Temperature>(false)
                              // closestTargetEntityArray = closestTargetEntityArray
        };

        // targetArray.Dispose();

        // state.Dependency = findTargetBurstJob.ScheduleSingle(targetQuery, state.Dependency);
        // JobHandle jobHandle = findTargetBurstJob.Schedule(this, inputDeps);
        Dependency = findTargetBurstJob.ScheduleParallel(targetQuery, 1, Dependency);
        // AddComponentJob addComponentJob = new AddComponentJob {
        //     closestTargetEntityArray = closestTargetEntityArray,
        //     entityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
        // };
        // jobHandle = addComponentJob.Schedule(this, jobHandle);

        // endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);

        // return jobHandle;
    }
Exemplo n.º 9
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityQuery query = GetEntityQuery(typeof(Target), ComponentType.ReadOnly <Translation>());

        NativeArray <Entity>      entities     = query.ToEntityArray(Allocator.TempJob);
        NativeArray <Translation> translations = query.ToComponentDataArray <Translation>(Allocator.TempJob);

        NativeArray <EntityWithPosition> entityWithPositions = new NativeArray <EntityWithPosition>(entities.Length, Allocator.TempJob);

        for (int i = 0; i < entityWithPositions.Length; i++)
        {
            entityWithPositions[i] = new EntityWithPosition
            {
                entity   = entities[i],
                position = translations[i].Value
            };
        }

        // Disponse native arrays
        entities.Dispose();
        translations.Dispose();

        EntityQuery          unitQuery      = GetEntityQuery(typeof(Unit), ComponentType.Exclude <HasTarget>());
        NativeArray <Entity> closestTargets = new NativeArray <Entity>(unitQuery.CalculateEntityCount(), Allocator.TempJob);

        //FindTargetBurstJob findTargetBurstJob = new FindTargetBurstJob
        //{
        //    targetArray = entityWithPositions,
        //    closestTargets = closestTargets
        //};
        //JobHandle handle = findTargetBurstJob.Schedule(this, inputDeps);

        FindTargetQuadrantSystemJob findTargetQuadrantSystemJob = new FindTargetQuadrantSystemJob
        {
            quadrantMap    = QuadrantSystem.quadrantMap,
            closestTargets = closestTargets
        };

        JobHandle handle = findTargetQuadrantSystemJob.Schedule(this, inputDeps);

        AddComponentJob addComponentJob = new AddComponentJob
        {
            closestTargets      = closestTargets,
            entityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent()
        };

        handle = addComponentJob.Schedule(this, handle);

        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(handle);

        return(handle);
    }
Exemplo n.º 10
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityQuery targetQuery = GetEntityQuery(new EntityQueryDesc()
            {
                All = new ComponentType[]
                {
                    typeof(EzTarget),
                    ComponentType.ReadOnly <Translation>()
                },
            });
            var         pArrayEntity      = targetQuery.ToEntityArray(Allocator.TempJob);
            var         pArrayTranslation = targetQuery.ToComponentDataArray <Translation>(Allocator.TempJob);
            var         pArrayEztarget    = targetQuery.ToComponentDataArray <EzTarget>(Allocator.TempJob);
            EntityQuery pUnitNontarget    = GetEntityQuery(typeof(EzUnit), typeof(Translation), ComponentType.Exclude <EzHasTarget>());
            var         pClosedFindEntity = new NativeArray <Entity>(pUnitNontarget.CalculateEntityCount(), Allocator.TempJob);

            NativeArray <EntityWithPosition> targetArray = new NativeArray <EntityWithPosition>(pArrayEntity.Length, Allocator.TempJob);

            for (int i = 0; i < pArrayEntity.Length; ++i)
            {
                targetArray[i] = new EntityWithPosition()
                {
                    entity   = pArrayEntity[i],
                    layer    = pArrayEztarget[i].layer.layer,
                    position = pArrayTranslation[i].Value
                };
            }
            pArrayEntity.Dispose();
            pArrayTranslation.Dispose();
            pArrayEztarget.Dispose();
            FindTargetJob jobFind = new FindTargetJob()
            {
                targetArray = targetArray,
                closestTargetEntityArray = pClosedFindEntity
            };
            var pAddComponentJob = new AddComponentJob()
            {
                entityCommandBuffer      = commandBufferSystem.CreateCommandBuffer().ToConcurrent(),
                closestTargetEntityArray = pClosedFindEntity,
            };
            JobHandle pJob = jobFind.Schedule(this, inputDeps);

            pJob = pAddComponentJob.Schedule(this, pJob);
            commandBufferSystem.AddJobHandleForProducer(pJob);
            return(pJob);
        }
Exemplo n.º 11
0
        private void FindTarget(int entityIndex, int hashMapKey, EntityDescription entityDesc, ref EntityWithPosition closestDangerTarget, ref float closestDangerTargetDistance,
                                ref EntityWithPosition closestFoodTarget, ref float closestFoodTargetDistance)
        {
            QuadrantData quadrantData;
            NativeMultiHashMapIterator <int> nativeMultiHashMapIterator;

            if (quadrantMultiHashMap.TryGetFirstValue(hashMapKey, out quadrantData, out nativeMultiHashMapIterator))
            {
                do
                {
                    var canHear = Helper.CanHear(quadrantData.position, entityDesc.location.Position, quadrantData.soundRadius);
                    var canSee  = Helper.CanSee(quadrantData.position, entityDesc.location, entityDesc.sight.angle);
                    var canSeeWithDoubleAngle = Helper.CanSee(quadrantData.position, entityDesc.location, entityDesc.sight.angle * 2);

                    // Check that it's different entity
                    if (quadrantData.entity.Index != entityIndex)
                    {
                        // Если видит врага или слышит его и при оглядывании видит или видит при оглядывании спасаясь от опасности
                        if (canSee || (canHear && canSeeWithDoubleAngle) || (entityDesc.lifeStatus.status == LivingStatus.LookAround && canSeeWithDoubleAngle))
                        {
                            var closestTargetStatus = TargetStatus.Neutral;

                            if (Helper.CanEat(entityDesc.size, entityDesc.diet, quadrantData.size, quadrantData.diet))
                            {
                                closestTargetStatus = TargetStatus.Food;
                            }
                            if (Helper.CanEat(quadrantData.size, quadrantData.diet, entityDesc.size, entityDesc.diet))
                            {
                                closestTargetStatus = TargetStatus.Danger;
                            }

                            if (closestTargetStatus == TargetStatus.Danger)
                            {
                                ChangeClosestTarget(ref closestDangerTarget, ref closestDangerTargetDistance, quadrantData, entityDesc);
                            }
                            if (closestTargetStatus == TargetStatus.Food)
                            {
                                ChangeClosestTarget(ref closestFoodTarget, ref closestFoodTargetDistance, quadrantData, entityDesc);
                            }
                        }
                    }
                } while (quadrantMultiHashMap.TryGetNextValue(out quadrantData, ref nativeMultiHashMapIterator));
            }
        }
Exemplo n.º 12
0
    private static EntityWithPosition FindClosestPosition(EntityWithPosition thisEntityWithPosition, float detectionDistanceSquare, EntityWithPosition currentClosestEntity, EntityWithPosition tryNewEntity)
    {
        if (thisEntityWithPosition.entity == tryNewEntity.entity)
        {
            return(currentClosestEntity);
        }

        float distancesq = math.distancesq(thisEntityWithPosition.position, tryNewEntity.position);

        var inDetectionDistance = distancesq < detectionDistanceSquare;

        if (currentClosestEntity.entity == Entity.Null & inDetectionDistance)
        {
            return(tryNewEntity);
        }
        var nearest = distancesq < math.distancesq(thisEntityWithPosition.position, currentClosestEntity.position);

        return(inDetectionDistance && nearest ? tryNewEntity : currentClosestEntity);
    }
Exemplo n.º 13
0
            public void Execute(Entity npc, int index, [ReadOnly] ref Translation translation)
            {
                float3 npcPos = translation.Value;

                float  minDistance = float.MaxValue;
                Entity target      = Entity.Null;

                for (int i = 0; i < TargetArray.Length; i++)
                {
                    EntityWithPosition ent = TargetArray[i];
                    float distance         = math.length(npcPos - ent.Position);
                    if (distance < minDistance)
                    {
                        target      = ent.Entity;
                        minDistance = distance;
                    }
                }

                SelectedTargets[index] = target;
            }
Exemplo n.º 14
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityQuery               eq           = GetEntityQuery(typeof(TargetTag), ComponentType.ReadOnly <Translation>());
            NativeArray <Entity>      entities     = eq.ToEntityArray(Allocator.TempJob);
            NativeArray <Translation> translations = eq.ToComponentDataArray <Translation>(Allocator.TempJob);

            NativeArray <EntityWithPosition> targetEntitysWithPosition = new NativeArray <EntityWithPosition>(entities.Length, Allocator.TempJob);

            for (int i = 0; i < entities.Length; i++)
            {
                targetEntitysWithPosition[i] = new EntityWithPosition()
                {
                    Entity   = entities[i],
                    Position = translations[i].Value
                };
            }

            entities.Dispose();
            translations.Dispose();

            NativeArray <Entity> foundTargets = new NativeArray <Entity>(
                GetEntityQuery(typeof(NPCTag), ComponentType.Exclude <HasTarget>()).CalculateEntityCount(),
                Allocator.TempJob);

            FindTargetJob findTargetJob = new FindTargetJob()
            {
                TargetArray     = targetEntitysWithPosition,
                SelectedTargets = foundTargets
            };
            JobHandle findTargetJobHandle = findTargetJob.Schedule(this, inputDeps);

            SetTargetJob setTargetJob = new SetTargetJob()
            {
                EntityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
                TargetArray         = foundTargets
            };
            JobHandle setTargetJobHandle = setTargetJob.Schedule(this, findTargetJobHandle);

            endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(setTargetJobHandle);
            return(setTargetJobHandle);
        }
Exemplo n.º 15
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityQuery               enemyEntityQuery      = GetEntityQuery(typeof(EnemyComponent), ComponentType.ReadOnly <Translation>());
        NativeArray <Entity>      enemyEntityArray      = enemyEntityQuery.ToEntityArray(Allocator.TempJob);
        NativeArray <Translation> enemyTranslationArray = enemyEntityQuery.ToComponentDataArray <Translation>(Allocator.TempJob);

        NativeArray <EntityWithPosition> enemyEntityWithPositionArray = new NativeArray <EntityWithPosition>(enemyEntityArray.Length, Allocator.TempJob);

        for (int i = 0; i < enemyEntityArray.Length; i++)
        {
            enemyEntityWithPositionArray[i] = new EntityWithPosition {
                entity   = enemyEntityArray[i],
                position = enemyTranslationArray[i].Value
            };
        }
        enemyEntityArray.Dispose();
        enemyTranslationArray.Dispose();

        EntityQuery soldierEntityQuery = GetEntityQuery(typeof(SoldierComponent), ComponentType.ReadOnly <Translation>());

        NativeArray <Entity> closestEntityArray = new NativeArray <Entity>(soldierEntityQuery.CalculateEntityCount(), Allocator.TempJob);
        FindEnemyJob         findEnemyJob       = new FindEnemyJob {
            enemyEntityWithPositionArray = enemyEntityWithPositionArray,
            closestEntityArray           = closestEntityArray,
        };


        AddHasEnemyComponentJob addHasEnemyComponentJob = new AddHasEnemyComponentJob {
            closestEntityArray  = closestEntityArray,
            entityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
        };


        JobHandle jobHandle = findEnemyJob.Schedule(this, inputDeps);

        jobHandle = addHasEnemyComponentJob.Schedule(this, jobHandle);

        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);
        return(jobHandle);
    }
Exemplo n.º 16
0
 private static void ChangeClosestTarget(ref EntityWithPosition closestTarget, ref float closestTargetDistance, QuadrantData quadrantData, EntityDescription entityDesc)
 {
     if (closestTarget.entity == Entity.Null)
     {
         // No target
         closestTarget = new EntityWithPosition {
             entity = quadrantData.entity, position = quadrantData.position
         };
         closestTargetDistance = math.distancesq(entityDesc.location.Position, quadrantData.position);
     }
     else
     {
         if (math.distancesq(entityDesc.location.Position, quadrantData.position) < closestTargetDistance)
         {
             // This target is closer
             closestTarget = new EntityWithPosition {
                 entity = quadrantData.entity, position = quadrantData.position
             };
             closestTargetDistance = math.distancesq(entityDesc.location.Position, quadrantData.position);
         }
     }
 }
Exemplo n.º 17
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var playerQuery           = GetEntityQuery(typeof(PlayerComponent), ComponentType.ReadOnly <Translation>());
            var playerEntities        = playerQuery.ToEntityArray(Allocator.TempJob);
            var translationComponents = playerQuery.ToComponentDataArray <Translation>(Allocator.TempJob);

            var playerTranslationArray = new NativeArray <EntityWithPosition>(translationComponents.Length, Allocator.TempJob);

            for (var i = 0; i < translationComponents.Length; i++)
            {
                playerTranslationArray[i] = new EntityWithPosition {
                    Entity   = playerEntities[i],
                    Position = translationComponents[i].Value,
                };
            }

            playerEntities.Dispose();
            translationComponents.Dispose();

            var collidedEntityArray     = new NativeArray <Entity>(playerQuery.CalculateEntityCount(), Allocator.TempJob);
            var playerCollisionBurstJob = new PlayerCollisionBurstJob
            {
                PlayerEntityArray   = playerTranslationArray,
                CollidedEntityArray = collidedEntityArray,
            };

            var handleCollisionJob = new HandleCollisionJob
            {
                CollidedEntityArray = collidedEntityArray,
                EntityCommandBuffer = _endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent()
            };

            var playerCollisionBurstJobHandle = playerCollisionBurstJob.Schedule(this, inputDeps);
            var handleCollisionJobHandle      = handleCollisionJob.Schedule(this, playerCollisionBurstJobHandle);

            _endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(handleCollisionJobHandle);

            return(handleCollisionJobHandle);
        }
Exemplo n.º 18
0
        public void Execute(Entity entity, int index, [ReadOnly] ref Sight sight,
                            [ReadOnly] ref LocalToWorld location, [ReadOnly] ref QuadrantEntity quadrantEntity, [ReadOnly] ref Diet diet,
                            [ReadOnly] ref AnimalSize size, [ReadOnly] ref LifeStatus lifeStatus)
        {
            EntityWithPosition closestDangerTarget = new EntityWithPosition {
                entity = Entity.Null
            };
            float closestDangerTargetDistance    = float.MaxValue;
            EntityWithPosition closestFoodTarget = new EntityWithPosition {
                entity = Entity.Null
            };
            float closestFoodTargetDistance = float.MaxValue;
            int   hashMapKey = QuadrantSystem.GetPositionHashMapKey(location.Position);

            var entityDesc = new EntityDescription()
            {
                sight          = sight,
                diet           = diet,
                location       = location,
                quadrantEntity = quadrantEntity,
                size           = size,
                lifeStatus     = lifeStatus
            };


            FindTarget(index, hashMapKey, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey + 1, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey - 1, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey + QuadrantSystem.quadrantYMultiplier, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey - QuadrantSystem.quadrantYMultiplier, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey + 1 + QuadrantSystem.quadrantYMultiplier, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey - 1 + QuadrantSystem.quadrantYMultiplier, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey + 1 - QuadrantSystem.quadrantYMultiplier, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);
            FindTarget(index, hashMapKey - 1 - QuadrantSystem.quadrantYMultiplier, entityDesc, ref closestDangerTarget, ref closestDangerTargetDistance, ref closestFoodTarget, ref closestFoodTargetDistance);

            closestDangerTargetArray[index] = closestDangerTarget;
            closestFoodTargetArray[index]   = closestFoodTarget;
        }
Exemplo n.º 19
0
        public void Execute(Entity entity, int index, [ReadOnly] ref Translation translation)
        {
            float3 unitPosition          = translation.Value;
            Entity closestTargetEntity   = Entity.Null;
            float3 closestTargetPosition = float3.zero;

            for (int i = 0; i < targetArray.Length; i++)
            {
                // Cycling through all target entities
                EntityWithPosition targetEntityWithPosition = targetArray[i];

                if (closestTargetEntity == Entity.Null)
                {
                    // No target
                    closestTargetEntity   = targetEntityWithPosition.entity;
                    closestTargetPosition = targetEntityWithPosition.position;
                }
                else
                {
                    if (math.distance(unitPosition, targetEntityWithPosition.position) < math.distance(unitPosition, closestTargetPosition))
                    {
                        // This target is closer
                        closestTargetEntity   = targetEntityWithPosition.entity;
                        closestTargetPosition = targetEntityWithPosition.position;
                    }
                }
            }

            // Closest Target
            if (closestTargetEntity != Entity.Null)
            {
                entityCommandBuffer.AddComponent(index, entity, new HasTarget {
                    targetEntity = closestTargetEntity
                });
            }
        }
Exemplo n.º 20
0
    protected override JobHandle OnUpdate(JobHandle inputDebs)
    {
        NativeArray <EntityWithPosition> asteroidPositions = new NativeArray <EntityWithPosition>(_asteroidsQuery.CalculateEntityCount(), Allocator.TempJob);

        JobHandle jobHandle = Entities.WithAll <Tag_Asteroid>().ForEach((Entity entity, int entityInQueryIndex, in Translation translation) =>
        {
            asteroidPositions[entityInQueryIndex] = new EntityWithPosition
            {
                entity   = entity,
                position = translation.Value
            };
        }).Schedule(inputDebs);

        NativeArray <EntityWithPosition> ufoPositions = new NativeArray <EntityWithPosition>(_ufoQuery.CalculateEntityCount(), Allocator.TempJob);

        jobHandle = Entities.WithAll <Tag_Ufo>().ForEach((Entity entity, int entityInQueryIndex, in Translation translation) =>
        {
            ufoPositions[entityInQueryIndex] = new EntityWithPosition
            {
                entity   = entity,
                position = translation.Value
            };
        }).Schedule(jobHandle);

        jobHandle = Entities.ForEach((Entity entity, ref DetectorComponent detector, in Translation translation) =>
        {
            EntityWithPosition closestAsteroid = new EntityWithPosition {
                entity = Entity.Null, position = float3.zero
            };
            EntityWithPosition closestUfo = new EntityWithPosition {
                entity = Entity.Null, position = float3.zero
            };

            EntityWithPosition thisEntityWithPosition = new EntityWithPosition
            {
                entity   = entity,
                position = translation.Value
            };
            float asteroidDetectionDistanceSquare = detector.asteroidDetectionDistance * detector.asteroidDetectionDistance;

            for (int i = 0; i < asteroidPositions.Length; i++)
            {
                closestAsteroid = FindClosestPosition(thisEntityWithPosition, asteroidDetectionDistanceSquare, closestAsteroid, asteroidPositions[i]);
            }

            float ufoDetectionDistanceSquare = detector.ufoDetectionDistance * detector.asteroidDetectionDistance;

            for (int i = 0; i < ufoPositions.Length; i++)
            {
                closestUfo = FindClosestPosition(thisEntityWithPosition, ufoDetectionDistanceSquare, closestUfo, ufoPositions[i]);
            }

            detector.closestAsteroidEntity = closestAsteroid.entity;
            detector.closestUfoEntity      = closestUfo.entity;
        }).Schedule(jobHandle);

        jobHandle = asteroidPositions.Dispose(jobHandle);
        jobHandle = ufoPositions.Dispose(jobHandle);

        return(jobHandle);
    }
        // public NativeArray<Entity> closestTargetEntityArray;

        public void Execute(ArchetypeChunk chunk, int chunkIndex)  //[ReadOnly] ref Translation translation, ref Temperature temperature) {
        {
            var chunkTranslations = chunk.GetNativeArray(TranslationType);
            var chunkTemperatures = chunk.GetNativeArray(TemperatureType);



            //iterate through each entity in this chunk
            for (int i = 0; i < chunk.Count; i++)
            {
                float       tempDiffSum = 0;
                Translation translation = chunkTranslations[i];
                Temperature temperature = chunkTemperatures[i];

                //iterate through all other entities
                for (int j = 0; j < targetArray.Length; j++)
                {
                    // Cycling through all target entities
                    EntityWithPosition targetEntityWithPosition = targetArray[j];

                    float distanceToOtherEntity = math.distance(translation.Value, targetEntityWithPosition.position);
                    if (distanceToOtherEntity < 3 && distanceToOtherEntity != 0)
                    {
                        // Debug.Log("distance " + distanceToOtherEntity);

                        float temperatureDiff = temperature.Value - targetEntityWithPosition.temperature;
                        tempDiffSum += temperatureDiff * deltaTime;
                    }
                }
                // Debug.Log("diff: " + tempDiffSum + " before: " + temperature.Value + " after: " + (temperature.Value-tempDiffSum));
                chunkTemperatures[i] = new Temperature {
                    Value = temperature.Value - tempDiffSum,
                    Rate  = temperature.Rate
                };
            }


            // float3 unitPosition = translation.Value;
            // float unitTemperature = temperature.Value;
            // // Entity closestTargetEntity = Entity.Null;
            // // float3 closestTargetPosition = float3.zero;
            // // float3 closestTargetTemperature = 0;

            // float tempDiffSum = 0;
            // for (int i=0; i<targetArray.Length; i++) {
            //     // Cycling through all target entities
            //     EntityWithPosition targetEntityWithPosition = targetArray[i];

            //     float distanceToOtherEntity = math.distance(unitPosition, targetEntityWithPosition.position);
            //     float temperatureDiff = unitTemperature - targetEntityWithPosition.temperature;
            //     tempDiffSum += temperatureDiff;

            //     if (closestTargetEntity == Entity.Null) {
            //         // No target
            //         closestTargetEntity = targetEntityWithPosition.entity;
            //         closestTargetPosition = targetEntityWithPosition.position;
            //     } else {
            //         if (math.distance(unitPosition, targetEntityWithPosition.position) < math.distance(unitPosition, closestTargetPosition)) {
            //             // This target is closer
            //             closestTargetEntity = targetEntityWithPosition.entity;
            //             closestTargetPosition = targetEntityWithPosition.position;
            //             closestTargetTemperature = targetEntityWithPosition.temperature;
            //         }
            //     }
            // }
            // temperature.Value += tempDiffSum * .01;

            // closestTargetEntityArray[index] = closestTargetEntity;
        }
Exemplo n.º 22
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityCommandBuffer.Concurrent concurrentCommandBuffer = _endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent();

            EntityQuery               targetQuery            = GetEntityQuery(typeof(Target), ComponentType.Exclude <BeingUsed>(), ComponentType.ReadOnly <Translation>());
            NativeArray <Entity>      targetEntityArray      = targetQuery.ToEntityArray(Allocator.TempJob);
            NativeArray <Translation> targetTranslationArray = targetQuery.ToComponentDataArray <Translation>(Allocator.TempJob);

            NativeArray <EntityWithPosition> targetArray = new NativeArray <EntityWithPosition>(targetEntityArray.Length, Allocator.TempJob);

            for (int i = 0; i < targetEntityArray.Length; i++)
            {
                targetArray[i] = new EntityWithPosition
                {
                    Entity   = targetEntityArray[i],
                    Position = targetTranslationArray[i].Value
                };
            }

            JobHandle jobHandle = Entities
                                  .WithAll <Unit>()
                                  .WithNone <HasTarget>()
                                  .ForEach((int entityInQueryIndex, Entity entity, ref Translation unitTranslation) => {
                Entity closestTargetEntity   = Entity.Null;
                float3 unitPosition          = unitTranslation.Value;
                float3 closestTargetPosition = float3.zero;

                for (var i = 0; i < targetArray.Length; i++)
                {
                    EntityWithPosition entityWithPosition = targetArray[i];

                    if (closestTargetEntity == Entity.Null)
                    {
                        closestTargetEntity   = entityWithPosition.Entity;
                        closestTargetPosition = entityWithPosition.Position;
                    }
                    else
                    {
                        if (math.distance(unitPosition, entityWithPosition.Position) <
                            math.distance(unitPosition, closestTargetPosition))
                        {
                            closestTargetEntity   = entityWithPosition.Entity;
                            closestTargetPosition = entityWithPosition.Position;
                        }
                    }
                }

                if (closestTargetEntity != Entity.Null)
                {
                    concurrentCommandBuffer.AddComponent(entityInQueryIndex, entity, new HasTarget
                    {
                        TargetEntity   = closestTargetEntity,
                        TargetPosition = closestTargetPosition
                    });

                    concurrentCommandBuffer.AddComponent <BeingUsed>(entityInQueryIndex, closestTargetEntity);
                }
            }).Schedule(inputDeps);

            _endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);

            targetEntityArray.Dispose();
            targetTranslationArray.Dispose();

            return(jobHandle);
        }
Exemplo n.º 23
0
        public void Execute(Entity entity, int index, [ReadOnly] ref Translation skeletonTranslation, ref PhysicsVelocity velocity)
        {
            Skeleton unit;
            float    slowingDistance       = 10;
            float    moveSpeed             = 8;
            float    separation_radius_min = 5;
            float    separation_radius_max = 10;
            int      areaUnitsCount        = 0;

            float3 sepVelocity    = new float3(0, 0, 0);
            float3 alignVelocity  = new float3(0, 0, 0);
            float3 arriveVelocity = new float3(0, 0, 0);
            float3 velocitySum    = new float3(0, 0, 0);

            //Code to run on all entities with the "Skeleton" tag
            NativeList <Entity>  closestTargetsEntityList   = new NativeList <Entity>(Allocator.Temp);
            NativeList <float3>  closestTargetsPositionList = new NativeList <float3>(Allocator.Temp);
            NativeList <Vector3> closestTargetsVelocityList = new NativeList <Vector3>(Allocator.Temp);
            float3 skeletonPosition      = skeletonTranslation.Value;
            float3 closestTargetPosition = float3.zero;

            float velocity_magnitude = Vector3.Magnitude(velocity.Linear) / moveSpeed;
            float separation_radius  = math.lerp(separation_radius_min, separation_radius_max, velocity_magnitude);

            unit.unitStatus = UnitStatus.Idle;

            for (int i = 0; i < targetArray.Length; i++)
            {
                EntityWithPosition targetEntity = targetArray[i];

                //Cycle through all other skeletons units to find the ones in neighbour distance

                if (entity != null)
                {
                    if (entity != targetEntity.entity)
                    {
                        if (math.lengthsq(targetEntity.position - skeletonPosition) < (separation_radius * separation_radius))
                        {
                            closestTargetsEntityList.Add(targetEntity.entity);
                            closestTargetsPositionList.Add(targetEntity.position);
                            closestTargetsVelocityList.Add(targetEntity.velocity.Angular);
                        }
                    }
                }
            }

            sepVelocity = doSeparation(closestTargetsEntityList, closestTargetsPositionList, skeletonPosition, moveSpeed, velocity.Linear);

            arriveVelocity = doArrival(tempTarget, skeletonPosition, moveSpeed, velocity.Linear);
            velocitySum    = (sepVelocity + arriveVelocity + alignVelocity) * new float3(1, 0, 1);

            if (!(velocitySum.Equals(float3.zero)))
            {
                velocity.Linear += math.normalize(velocitySum);
            }


            closestTargetsEntityList.Dispose();
            closestTargetsPositionList.Dispose();
            closestTargetsVelocityList.Dispose();
        }