private static Entity ClosestStoreWith(NativeArray <StoreBufferElement> stores, FixedString32 resourceName, Entity entity,
                                           ComponentDataFromEntity <Translation> translationData, BufferFromEntity <InventoryBufferElement> inventoryData)
    {
        Entity closestStore         = default;
        float  closestStoreDistance = 0f;
        bool   firstFlag            = true;
        var    entityTranslation    = translationData[entity].Value;

        for (int i = 0; i < stores.Length; i++)
        {
            var store     = stores[i];
            var inventory = inventoryData[store.Location];
            if (inventory.GetAmountOf(resourceName) >= portion)
            {
                var storeDistance = Distance(translationData[store.Location].Value, entityTranslation);
                if (firstFlag || storeDistance < closestStoreDistance)
                {
                    closestStore         = store.Location;
                    closestStoreDistance = Distance(entityTranslation, translationData[store.Location].Value);
                    firstFlag            = false;
                }
            }
        }
        return(closestStore);
    }
Beispiel #2
0
    /// <summary>
    /// Performs a collider cast along the specified ray.<para/>
    ///
    /// Will return true if there was a collision and populate the provided <see cref="ColliderCastHit"/>.
    /// </summary>
    /// <param name="nearestHit"></param>
    /// <param name="collider"></param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <param name="collisionWorld"></param>
    /// <param name="ignore"></param>
    /// <param name="filter">Used to exclude collisions that do not match the filter.</param>
    /// <param name="manager">Required if specifying a collision filter. Otherwise is unused.</param>
    /// <param name="colliderData">Alternative to the EntityManager if used in a job.</param>
    /// <returns></returns>
    public unsafe static bool ColliderCast(
        out ColliderCastHit nearestHit,
        PhysicsCollider collider,
        float3 from,
        float3 to,
        ref CollisionWorld collisionWorld,
        Entity ignore,
        CollisionFilter?filter = null,
        EntityManager?manager  = null,
        ComponentDataFromEntity <PhysicsCollider>?colliderData = null,
        Allocator allocator = Allocator.TempJob)
    {
        nearestHit = new ColliderCastHit();
        NativeList <ColliderCastHit> allHits = ColliderCastAll(collider, from, to, ref collisionWorld, ignore, allocator);

        if (filter.HasValue)
        {
            if (manager.HasValue)
            {
                TrimByFilter(ref allHits, manager.Value, filter.Value);
            }
            else if (colliderData.HasValue)
            {
                TrimByFilter(ref allHits, colliderData.Value, filter.Value);
            }
        }

        GetSmallestFractional(ref allHits, out nearestHit);
        allHits.Dispose();

        return(true);
    }
        static void HandleCompletePath(ComponentDataFromEntity <LocalToWorld> localToWorldFromEntity, Entity entity, Rotation rotation, ref NavAgent agent, Parent surface, Translation translation, PhysicsWorld physicsWorld, float elapsedSeconds, EntityCommandBuffer.ParallelWriter commandBuffer, int entityInQueryIndex, NavSettings settings)
        {
            var rayInput = new RaycastInput
            {
                Start  = localToWorldFromEntity[entity].Position + agent.Offset,
                End    = math.forward(rotation.Value) * settings.ObstacleRaycastDistanceMax,
                Filter = new CollisionFilter
                {
                    BelongsTo    = NavUtil.ToBitMask(settings.ColliderLayer),
                    CollidesWith = NavUtil.ToBitMask(settings.ObstacleLayer)
                }
            };

            if (
                !surface.Value.Equals(agent.DestinationSurface) &&
                !NavUtil.ApproxEquals(translation.Value, agent.LocalDestination, settings.StoppingDistance) &&
                !physicsWorld.CastRay(rayInput, out _)
                )
            {
                agent.JumpSeconds = elapsedSeconds;

                commandBuffer.RemoveComponent <NavWalking>(entityInQueryIndex, entity);
                commandBuffer.RemoveComponent <NavSteering>(entityInQueryIndex, entity);
                commandBuffer.AddComponent <NavJumping>(entityInQueryIndex, entity);
                commandBuffer.AddComponent <NavPlanning>(entityInQueryIndex, entity);

                return;
            }

            commandBuffer.RemoveComponent <NavWalking>(entityInQueryIndex, entity);
            commandBuffer.RemoveComponent <NavSteering>(entityInQueryIndex, entity);
            commandBuffer.RemoveComponent <NavDestination>(entityInQueryIndex, entity);
        }
Beispiel #4
0
 static public T2 Get <T0, T1, T2, T3>
     (this ComponentDataFromEntity <T2> componentDataFromEntity, ITypedEntity <T0, T1, T2, T3> entity)
     where T0 : struct, IComponentData
     where T1 : struct, IComponentData
     where T2 : struct, IComponentData
     where T3 : struct, IComponentData
 => componentDataFromEntity[entity.Entity];
Beispiel #5
0
    public override void UpdateSystem()
    {
        ComponentDataFromEntity <Translation> translationLookup = GetComponentDataFromEntity <Translation>();
        ComponentDataFromEntity <Health>      healthLookup      = GetComponentDataFromEntity <Health>();

        Entities.WithAll <MovingToAttackState>().ForEach((ref DynamicBuffer <Command> commandBuffer, ref UnitMove unitMove, ref PhysicsVelocity physicsVelocity, ref CurrentTarget currentTarget,
                                                          in Translation translation, in CombatUnit combatUnit) =>
        {
            Translation targetTranslation = translationLookup[currentTarget.targetData.targetEntity];

            //If our target has moved, update our target pos.
            if (!targetTranslation.Value.Equals(currentTarget.targetData.targetPos))
            {
                currentTarget.targetData.targetPos = targetTranslation.Value;
            }

            float distance = math.distance(translation.Value, currentTarget.targetData.targetPos);

            //We are in range, execute attack command.
            if (distance < combatUnit.attackRange)
            {
                CommandProcessSystem.ExecuteCommand(ref commandBuffer);

                unitMove.rotating      = false;
                physicsVelocity.Linear = 0;
            }
        }).ScheduleParallel();
Beispiel #6
0
 public void BeginSerialize(ComponentSystemBase system)
 {
     componentTypePlayerCommandData    = ComponentType.ReadWrite <PlayerCommandData>();
     componentTypePhysicsCollider      = ComponentType.ReadWrite <PhysicsCollider>();
     componentTypePhysicsGravityFactor = ComponentType.ReadWrite <PhysicsGravityFactor>();
     componentTypePhysicsMass          = ComponentType.ReadWrite <PhysicsMass>();
     componentTypePhysicsVelocity      = ComponentType.ReadWrite <PhysicsVelocity>();
     componentTypeLocalToWorld         = ComponentType.ReadWrite <LocalToWorld>();
     componentTypeRotation             = ComponentType.ReadWrite <Rotation>();
     componentTypeTranslation          = ComponentType.ReadWrite <Translation>();
     componentTypeLinkedEntityGroup    = ComponentType.ReadWrite <LinkedEntityGroup>();
     ghostPlayerCommandDataType        = system.GetArchetypeChunkComponentType <PlayerCommandData>(true);
     ghostRotationType          = system.GetArchetypeChunkComponentType <Rotation>(true);
     ghostTranslationType       = system.GetArchetypeChunkComponentType <Translation>(true);
     ghostLinkedEntityGroupType = system.GetArchetypeChunkBufferType <LinkedEntityGroup>(true);
     ghostChild0RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild0TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild1RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild1TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild2RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild2TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild3RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild3TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild4RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild4TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild5RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild5TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild6RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild6TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild7RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild7TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild8RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild8TranslationType = system.GetComponentDataFromEntity <Translation>(true);
 }
 static void SetComponentDataValueByMethod(ComponentDataFromEntity <EcsTestData> cdfe, Entity entity, int value)
 {
     cdfe[entity] = new EcsTestData()
     {
         value = value
     };
 }
    protected override JobHandle OnUpdate(JobHandle handle)
    {
        ComponentDataFromEntity <Translation> allTranslation = GetComponentDataFromEntity <Translation>();

        handle = new SoliderContactJob
        {
            allTranslation  = allTranslation,
            aliveFromEntity = GetComponentDataFromEntity <SoldierAlive>(),
            CommandBuffer   = endSimCmd.CreateCommandBuffer().ToConcurrent()
        }.Schedule(this, handle);

        // Job that remove the target
        handle = new RemoveInvalidTargets
        {
            CommandBuffer      = endSimCmd.CreateCommandBuffer().ToConcurrent(),
            PositionFromEntity = GetComponentDataFromEntity <Translation>()
        }.Schedule(this, handle);

        // Job that Destroy entities
        handle = new RemoveDeadSoldiers
        {
            CommandBuffer = endSimCmd.CreateCommandBuffer().ToConcurrent()
        }.Schedule(this, handle);


        // setup the endsimCMD
        endSimCmd.AddJobHandleForProducer(handle);

        return(handle);
    }
    public override int NativeToInteger(object value, ComponentDataFromEntity <NetworkSyncState> networkSyncStateEntities)
    {
        Entity           entity            = (Entity)value;
        NetworkSyncState networkSynchState = networkSyncStateEntities[entity];

        return(NetworkUtility.GetNetworkEntityHash(networkSynchState.actorId, networkSynchState.networkId));
    }
Beispiel #10
0
    protected override void OnUpdate()
    {
        var player = GetSingletonEntity <Player>();
        ComponentDataFromEntity <PhysicsVelocity> velocities = GetComponentDataFromEntity <PhysicsVelocity>();
        PhysicsVelocity velocity = velocities[player];

        if (isPaused)
        {
            if (!hasSaved)
            {
                hasSaved      = true;
                savedVelocity = velocity.Linear;
            }

            velocity.Linear = new float3
            {
                x = 0,
                y = 0,
                z = 0
            };
            velocities[player] = velocity;
        }
        else
        {
            velocity.Linear    = savedVelocity;
            velocities[player] = velocity;
            isPaused           = false;
            hasSaved           = false;
        }
    }
Beispiel #11
0
        protected override void OnUpdate()
        {
            Entity mapEntity = World.GetOrCreateSystem <MapSystem>().GetMapEntity();
            Grid   grid      = GetComponent <Grid>(mapEntity);
            DynamicBuffer <Cell>            cellBuffer      = GetBuffer <Cell>(mapEntity);
            ComponentDataFromEntity <Block> blockFromEntity = GetComponentDataFromEntity <Block>(true);

            EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.TempJob);

            Entities
            .WithReadOnly(blockFromEntity)
            .WithAll <TurnToken>()
            .ForEach((Entity entity, in ActorAction action, in Tile tile) =>
            {
                commandBuffer.RemoveComponent <ActorAction>(entity);

                int2 targetCoord = tile.GetCoord() + CommonUtils.DirectionToInt2(action.Direction);
                Entity target    = grid.GetUnit(cellBuffer.AsNativeArray(), targetCoord);
                if (target != Entity.Null)
                {
                    // Attack
                    commandBuffer.AddComponent(entity, new AttackCommand(target));
                }
                else if (grid.IsWalkable(blockFromEntity, cellBuffer.AsNativeArray(), targetCoord))
                {
                    // Move
                    commandBuffer.AddComponent(entity, new GridMoveCommand(targetCoord));
                }
                else
                {
                    return;
                }

                commandBuffer.RemoveComponent <TurnToken>(entity);
            }).Schedule();
Beispiel #12
0
            private bool TryGetEntity <T>(
                TriggerEvent triggerEvent,
                ComponentDataFromEntity <T> componentData,
                out Entity entity,
                out T component) where T : struct, IComponentData
            {
                entity    = default;
                component = default;

                if (componentData.Exists(triggerEvent.Entities.EntityA))
                {
                    entity    = triggerEvent.Entities.EntityA;
                    component = componentData[entity];
                    return(true);
                }

                if (componentData.Exists(triggerEvent.Entities.EntityB))
                {
                    entity    = triggerEvent.Entities.EntityB;
                    component = componentData[entity];
                    return(true);
                }

                return(false);
            }
Beispiel #13
0
    private bool GetComponentData <T>(ref Entity entity, out ComponentDataContainer componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType componentType   = ComponentType.Create <T>();
            int           numberOfMembers = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());
            ComponentDataFromEntity <NetworkSyncState> networkSyncStateEntities = EntityManager.GetComponentDataFromEntity <NetworkSyncState>();

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkMemberInfo[]        networkMemberInfos   = reflectionUtility.GetNetworkMemberInfo(componentType);
            List <MemberDataContainer> memberDataContainers = new List <MemberDataContainer>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                memberDataContainers.Add(new MemberDataContainer()
                {
                    MemberId = i,
                    Data     = (networkMemberInfos[i] as NetworkMemberInfo <T>).GetValue(component, networkSyncStateEntities)
                });
            }


            componentDataContainer = new ComponentDataContainer()
            {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType),
                MemberData      = memberDataContainers
            };
            return(true);
        }
        return(false);
    }
Beispiel #14
0
        public static bool GetClosestBlockOnSameLevel <T>(
            Random random,
            int2 point,
            ComponentDataFromEntity <Depth> sorter,
            ComponentDataFromEntity <T> filter,
            NativeHashMap <int2, Entity> map,
            NativeHashMap <int2, int> checkMap,
            NativeList <int2> buffer, int2 size,

            out int2 result) where T : struct, IComponentData
        {
            buffer.Clear();
            checkMap.Clear();
            result = new int2(-1, -1);
            CheckNeighbourBlocks(random, point, point, size, map, buffer, filter, checkMap);
            int2  origin  = point;
            float closest = int.MaxValue;

            for (int i = 0; i < buffer.Length; i++)
            {
                int2   p    = buffer[i];
                Entity e    = map[p];
                Depth  dist = sorter[e];
                if (dist.Value < closest && !origin.Equals(p))
                {
                    closest = dist.Value;
                    result  = p;
                }
            }
            return(result.x >= 0);
        }
Beispiel #15
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.TempJob);
            var prefabs             = new NativeArray <Entity>(_gravitySwitchPrefabs, Allocator.TempJob);
            ComponentDataFromEntity <CellLink> cellLinks = GetComponentDataFromEntity <CellLink>(true);
            ComponentDataFromEntity <Color>    colors    = GetComponentDataFromEntity <Color>(true);

            Entities
            .ForEach((Entity entity, DynamicBuffer <MatchGroupElement> matchGroup) =>
            {
                if (matchGroup.Length >= 4)
                {
                    var ballEntity = matchGroup[UnityEngine.Random.Range(0, matchGroup.Length)].BallEntity;
                    var color      = colors[ballEntity].Value;
                    var cellEntity = cellLinks[ballEntity].Value;
                    ecb.AddComponent(cellEntity, new Spawner {
                        Prefab = prefabs[color], Offset = float3.zero
                    });
                    ecb.AddComponent <SpawnCount>(cellEntity);
                    ecb.AddComponent(cellEntity, new SpawnLimit {
                        Value = 1
                    });
                }
            }).Run();

            prefabs.Dispose();
            ecb.Playback(EntityManager);
            ecb.Dispose();
            return(default);
Beispiel #16
0
    protected override void OnUpdate()
    {
        cTransGroup = GetComponentDataFromEntity <Translation>(true);

        Entities.ForEach((
                             ref Translation cTrans,
                             ref C_Controller_AI cAIControl,
                             ref C_AIBehavior_FollowEntity cBehavior,
                             ref C_Ability_CanControlLateralMovement cControlsMovement) =>
        {
            if (!EntityManager.Exists(cAIControl.targetEntity))
            {
                return;
            }

            if (Vector3.Distance(cTransGroup[cAIControl.targetEntity].Value, cTrans.Value) > distanceFromTargetToStopAt)
            {
                directionToTarget = cTransGroup[cAIControl.targetEntity].Value - cTrans.Value;
                cControlsMovement.normalizedLateralDir = directionToTarget.normalized;
            }
            else
            {
                cControlsMovement.normalizedLateralDir = new Vector3(0f, 0f, 0f).normalized;
            }
        });
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            // Debug.LogWarning ( "Col" ) ;
            Bounds checkBounds = new Bounds()
            {
                center = new float3(10, 2, 10),
                size   = new float3(1, 1, 1) * 5  // Total size of boundry
            };

            int i_firstEntity = 0;

            NativeArray <Entity> na_entities = group.ToEntityArray(Allocator.TempJob);
            Entity rootNodeEntity            = na_entities [i_firstEntity];

            na_entities.Dispose();

            ComponentDataFromEntity <RootNodeData> a_rootNodeData = GetComponentDataFromEntity <RootNodeData> (true);
            // ComponentDataArray <RootNodeData> a_rootNodeData       = group.GetComponentDataArray <RootNodeData> ( ) ;
            RootNodeData rootNode = a_rootNodeData [rootNodeEntity];

            BufferFromEntity <NodeBufferElement> nodeBufferElement = GetBufferFromEntity <NodeBufferElement> (true);
            DynamicBuffer <NodeBufferElement>    a_nodesBuffer     = nodeBufferElement [rootNodeEntity];


            Bounds maxBouds = _GetOctreeMaxBounds(ref rootNode, ref a_nodesBuffer);


            return(inputDeps);
        }
Beispiel #18
0
 //Returns true if entity is already on location, false if it is not
 private static bool GoToLocation(Entity location, Entity movedEntity, ComponentDataFromEntity <CurrentLocationComponent> currentLocationData,
                                  ComponentDataFromEntity <ExchangeTaskLocationComponent> exchangeTaskLocationData, EntityCommandBuffer.ParallelWriter ecb, int entityInQueryIndex)
 {
     if (location == movedEntity)
     {
         return(true);
     }
     if (!currentLocationData.HasComponent(movedEntity) || !(currentLocationData[movedEntity].entity == location))
     {
         var exchangeTaskLocation = new ExchangeTaskLocationComponent {
             Entity = location
         };
         if (exchangeTaskLocationData.HasComponent(movedEntity))
         {
             exchangeTaskLocationData[movedEntity] = exchangeTaskLocation;
         }
         else
         {
             ecb.AddComponent(entityInQueryIndex, movedEntity, exchangeTaskLocation);
         }
         return(false);
     }
     else
     {
         return(true);
     }
 }
Beispiel #19
0
        public static void UnJoinIfJoined(EntityCommandBuffer.Concurrent ecb,
                                          int jobIndex,
                                          ComponentDataFromEntity <LineJoinPoint> joinPoints,
                                          Entity oneSide)
        {
            var fromEntity = oneSide;
            var fromData   = joinPoints[oneSide];

            if (!fromData.IsJoined)
            {
                return;
            }

            var toEntity = fromData.JoinToPointEntity;

            if (!joinPoints.Exists(toEntity))
            {
                var toData = joinPoints[toEntity];
                toData.JoinToPointEntity = Entity.Null;
                ecb.SetComponent(jobIndex, toEntity, toData);
            }

            fromData.JoinToPointEntity = Entity.Null;
            ecb.SetComponent(jobIndex, fromEntity, fromData);
        }
Beispiel #20
0
    protected override void OnStartRunning()
    {
        // Retrieve Scene camera & associated Entity
        camera = Camera.main;
        Entities.ForEach((Entity e, ref CameraControlComponent control) =>
        {
            cameraControl = control;
        });

        // Retrieve & cache player Tank entities
        if (playersQuery.CalculateLength() == 0)
        {
            throw new InvalidOperationException("No tank player entities detected");
        }
        var players = playersQuery.ToEntityArray(Allocator.TempJob);
        {
            ComponentDataFromEntity <TankPlayer> tankPlayers = GetComponentDataFromEntity <TankPlayer>();
            for (int i = 0; i < players.Length; i++)
            {
                TankPlayer tankPlayer = tankPlayers[players[i]];
                if (tankPlayer.PlayerId == 0)
                {
                    player1Entity = players[i];
                }
                else if (tankPlayer.PlayerId == 1)
                {
                    player2Entity = players[i];
                }
            }
            players.Dispose();
        }
    }
 public void BeginSerialize(ComponentSystemBase system)
 {
     componentTypeHealth             = ComponentType.ReadWrite <Health>();
     componentTypePlayerUnit         = ComponentType.ReadWrite <PlayerUnit>();
     componentTypeUnitSelectionState = ComponentType.ReadWrite <UnitSelectionState>();
     componentTypePhysicsCollider    = ComponentType.ReadWrite <PhysicsCollider>();
     componentTypeCompositeScale     = ComponentType.ReadWrite <CompositeScale>();
     componentTypeLocalToWorld       = ComponentType.ReadWrite <LocalToWorld>();
     componentTypeRotation           = ComponentType.ReadWrite <Rotation>();
     componentTypeTranslation        = ComponentType.ReadWrite <Translation>();
     componentTypeLinkedEntityGroup  = ComponentType.ReadWrite <LinkedEntityGroup>();
     ghostHealthType             = system.GetArchetypeChunkComponentType <Health>(true);
     ghostPlayerUnitType         = system.GetArchetypeChunkComponentType <PlayerUnit>(true);
     ghostUnitSelectionStateType = system.GetArchetypeChunkComponentType <UnitSelectionState>(true);
     ghostRotationType           = system.GetArchetypeChunkComponentType <Rotation>(true);
     ghostTranslationType        = system.GetArchetypeChunkComponentType <Translation>(true);
     ghostLinkedEntityGroupType  = system.GetArchetypeChunkBufferType <LinkedEntityGroup>(true);
     ghostChild0RotationType     = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild0TranslationType  = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild1RotationType     = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild1TranslationType  = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild2RotationType     = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild2TranslationType  = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild3RotationType     = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild3TranslationType  = system.GetComponentDataFromEntity <Translation>(true);
 }
Beispiel #22
0
    public static CollisionData CalculateCollisionData(Entity entityA, Entity entityB,
                                                       ComponentDataFromEntity <CompositeScale> compositeScaleEntities,
                                                       ComponentDataFromEntity <Scale> scaleEntities,
                                                       ComponentDataFromEntity <Translation> translationEntities,
                                                       ComponentDataFromEntity <PhysicsCollider> colliderEntities)

    {
        var ret = new CollisionData();

        ret.EntityA = entityA;
        ret.EntityB = entityB;
        var translationA = translationEntities[entityA];
        var translationB = translationEntities[entityB];

        // Currently we use the translation's value as the center of the colliders.
        ret.ColliderBoundsA = GetBounds(translationA.Value, GetBoxColliderSize(colliderEntities[entityA]));
        ret.ColliderBoundsB = GetBounds(translationB.Value, GetBoxColliderSize(colliderEntities[entityB]));
        var overlapXMin = math.max(ret.ColliderBoundsA.Min.x, ret.ColliderBoundsB.Min.x);
        var overlapXMax = math.min(ret.ColliderBoundsA.Max.x, ret.ColliderBoundsB.Max.x);
        var overlapYMin = math.max(ret.ColliderBoundsA.Min.y, ret.ColliderBoundsB.Min.y);
        var overlapYMax = math.min(ret.ColliderBoundsA.Max.y, ret.ColliderBoundsB.Max.y);

        ret.OverlapX = overlapXMax - overlapXMin;
        ret.OverlapY = overlapYMax - overlapYMin;
        var signX = math.sign(translationA.Value.x - translationB.Value.x);

        ret.SignX = math.abs(signX) < float.Epsilon ? 1 : signX;
        var signY = math.sign(translationA.Value.y - translationB.Value.y);

        ret.SignY = math.abs(signY) < float.Epsilon ? 1 : signY;
        return(ret);
    }
Beispiel #23
0
 static public void Set <T0, T1, T2, T3>
     (this ComponentDataFromEntity <T3> componentDataFromEntity, ITypedEntity <T0, T1, T2, T3> entity, T3 componentData)
     where T0 : struct, IComponentData
     where T1 : struct, IComponentData
     where T2 : struct, IComponentData
     where T3 : struct, IComponentData
 => componentDataFromEntity[entity.Entity] = componentData;
Beispiel #24
0
    protected override void OnUpdate()
    {
        bool          goalReached = false;
        EntityManager manager     = World.EntityManager;
        Entity        player      = GetSingletonEntity <Player>();

        Entities.ForEach((Entity entity, ref Goal tag, ref Ground activation) =>
        {
            if (activation.playerWasHere)
            {
                goalReached = true;
            }
        });

        if (goalReached)
        {
            // Make the player entity stick to the platform
            ComponentDataFromEntity <PhysicsVelocity> physicsVelocity = GetComponentDataFromEntity <PhysicsVelocity>();
            PhysicsVelocity playerData = physicsVelocity[player];
            playerData.Linear = new Unity.Mathematics.float3 {
                x = 0, y = 0, z = 0
            };
            physicsVelocity[player] = playerData;
            GameManager.GetInstance().HasReachedGoal();
        }
    }
Beispiel #25
0
        protected override void OnUpdate()
        {
            float deltaTime = Time.DeltaTime;

            this.currentTime += deltaTime;

            if (this.currentTime >= UpdateInterval)
            {
                Entity seedEntity = this.GetEntityQuery(this.EntityManager.GetSeedIdentifier()).GetSingletonEntity();
                Random random     = new Random(this.EntityManager.GetComponentData <Seed>(seedEntity).Value);

                Entity      worldBoundsEntity = this.GetEntityQuery(this.EntityManager.GetWorldBoundsIdentifier()).GetSingletonEntity();
                WorldBounds worldBounds       = this.EntityManager.GetComponentData <WorldBounds>(worldBoundsEntity);

                EntityArchetype sfxArchetypeForJob = this.EntityManager.CreateSFXArchetype();

                //Assumes there is exactly 1 player
                Entity      playerEntity   = this.playerQuery.GetSingletonEntity();
                Translation playerPosition = this.EntityManager.GetComponentData <Translation>(playerEntity);
                ComponentDataFromEntity <MonsterRunTowardsPlayerTag> monsterRunTowardsPlayerComponentDataFromEntity = this.GetComponentDataFromEntity <MonsterRunTowardsPlayerTag>(true);

                EntityCommandBuffer.Concurrent entityCommandBuffer = this.endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent();

                this.Entities
                .WithAll <MonsterTag>()
                .ForEach((Entity monster, int entityInQueryIndex, ref PathfindingParameters pathfindingParameters, in Translation position, in MonsterInfo monsterInfo) =>
                {
                    //No attack tag yet added and player is withing agression radius
                    //Run towards player on grid, afterwards in MovementSystem, we run to the player position -> here we only run to the same grid cell.
                    if (!monsterRunTowardsPlayerComponentDataFromEntity.HasComponent(monster) && math.distance(position.Value, playerPosition.Value) <= monsterInfo.MonsterAgressionRadius)
                    {
                        entityCommandBuffer.AddComponent(entityInQueryIndex, monster, new MonsterRunTowardsPlayerTag());

                        //Choose playerPosition as destination on grid. Pathfinding grid is on x, z components (2d)
                        pathfindingParameters.StartPosition = worldBounds.WorldSpaceToCell(position.Value);
                        pathfindingParameters.EndPosition   = worldBounds.WorldSpaceToCell(playerPosition.Value);

                        pathfindingParameters.NeedsPathfindingCalculation = true;

                        //Add Monster Growl SFX
                        Entity sfx = entityCommandBuffer.CreateEntity(entityInQueryIndex, sfxArchetypeForJob);
                        entityCommandBuffer.SetComponent <SFXComponent>(entityInQueryIndex, sfx, new SFXComponent {
                            SFXType = SFXType.MonsterGrowl
                        });
                    }
                    else if (monsterRunTowardsPlayerComponentDataFromEntity.HasComponent(monster) && math.distance(position.Value, playerPosition.Value) > monsterInfo.MonsterAgressionRadius)
                    {
                        entityCommandBuffer.RemoveComponent(entityInQueryIndex, monster, ComponentType.ReadOnly <MonsterRunTowardsPlayerTag>());
                    }

                    //0.01% chance monster chooses new target node to walk to
                    if (!monsterRunTowardsPlayerComponentDataFromEntity.HasComponent(monster) && random.NextFloat() < 0.0001f)
                    {
                        //Choose position on grid. Pathfinding grid is on x, z components (2d)
                        pathfindingParameters.StartPosition = worldBounds.WorldSpaceToCell(position.Value);
                        pathfindingParameters.EndPosition   = random.NextInt2(new int2(0, 0), worldBounds.XZGridSize);

                        pathfindingParameters.NeedsPathfindingCalculation = true;
                    }
                })
Beispiel #26
0
 public PointCollisionJob(ComponentDataFromEntity <Point> pointEntities, ComponentDataFromEntity <Translation> translationEntities, Entity player, EntityCommandBuffer buffer)
 {
     this.player = player;
     this.translationEntities = translationEntities;
     this.pointEntities       = pointEntities;
     this.buffer = buffer;
 }
Beispiel #27
0
    /// <summary>
    /// Performs a collider cast using the specified collider.
    /// </summary>
    /// <param name="smallestDistanceHit"></param>
    /// <param name="collider"></param>
    /// <param name="maxDistance"></param>
    /// <param name="transform"></param>
    /// <param name="collisionWorld"></param>
    /// <param name="ignore"></param>
    /// <returns></returns>
    public static bool ColliderDistance(
        out DistanceHit smallestDistanceHit,
        PhysicsCollider collider,
        float maxDistance,
        RigidTransform transform,
        ref CollisionWorld collisionWorld,
        Entity ignore,
        CollisionFilter?filter = null,
        EntityManager?manager  = null,
        ComponentDataFromEntity <PhysicsCollider>?colliderData = null,
        Allocator allocator = Allocator.TempJob)
    {
        var allDistances = ColliderDistanceAll(collider, maxDistance, transform, ref collisionWorld, ignore, allocator);

        if (filter.HasValue)
        {
            if (manager.HasValue)
            {
                TrimByFilter(ref allDistances, manager.Value, filter.Value);
            }
            else if (colliderData.HasValue)
            {
                TrimByFilter(ref allDistances, colliderData.Value, filter.Value);
            }
        }

        GetSmallestFractional(ref allDistances, out smallestDistanceHit);
        allDistances.Dispose();

        return(true);
    }
Beispiel #28
0
 public MapStateJobContext(SystemBase sys, Entity e, bool readOnly = false)
 {
     entity = e;
     obstaclesFromEntity = sys.GetBufferFromEntity <MapObstaclesBuffer>(readOnly);
     entitiesFromEntity  = sys.GetBufferFromEntity <MapEntitiesBuffer>(readOnly);
     sizeFromEntity      = sys.GetComponentDataFromEntity <MapSize>(readOnly);
 }
Beispiel #29
0
        private void MovingToAttack(ComponentDataFromEntity <Translation> translationLookup)
        {
            Entities
            .WithReadOnly(translationLookup)
            .WithAll <MovingToAttackState>().
            ForEach((ref DynamicBuffer <Command> commandBuffer, ref UnitMove unitMove, ref PhysicsVelocity physicsVelocity, ref CurrentTarget currentTarget,
                     in Translation translation, in CombatUnit combatUnit) =>
            {
                Translation targetTranslation = translationLookup[currentTarget.targetData.targetEntity];

                //If our target has moved, update our target pos.
                if (!targetTranslation.Value.Equals(currentTarget.targetData.targetPos))
                {
                    currentTarget.targetData.targetPos = targetTranslation.Value;
                }

                //We are in range, execute attack command.
                if (IsInRange(combatUnit.attackRange, translation.Value, currentTarget.targetData.targetPos))
                {
                    CommandProcessSystem.ExecuteCommand(ref commandBuffer);

                    unitMove.rotating      = false;
                    physicsVelocity.Linear = 0;
                }
            }).ScheduleParallel();
 public void BeginSerialize(ComponentSystemBase system)
 {
     componentTypePilotData         = ComponentType.ReadWrite <PilotData>();
     componentTypeLocalToWorld      = ComponentType.ReadWrite <LocalToWorld>();
     componentTypeRotation          = ComponentType.ReadWrite <Rotation>();
     componentTypeTranslation       = ComponentType.ReadWrite <Translation>();
     componentTypeLinkedEntityGroup = ComponentType.ReadWrite <LinkedEntityGroup>();
     ghostPilotDataType             = system.GetArchetypeChunkComponentType <PilotData>(true);
     ghostRotationType          = system.GetArchetypeChunkComponentType <Rotation>(true);
     ghostTranslationType       = system.GetArchetypeChunkComponentType <Translation>(true);
     ghostLinkedEntityGroupType = system.GetArchetypeChunkBufferType <LinkedEntityGroup>(true);
     ghostChild0RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild0TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild1RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild1TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild2RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild2TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild3RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild3TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild4RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild4TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild5RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild5TranslationType = system.GetComponentDataFromEntity <Translation>(true);
     ghostChild6RotationType    = system.GetComponentDataFromEntity <Rotation>(true);
     ghostChild6TranslationType = system.GetComponentDataFromEntity <Translation>(true);
 }