private IEnumerator PlayerTurn()
    {
        isPlayerTurn = true;

        isAwaitingUserInput = true;

        while (isAwaitingUserInput)
        {
            yield return(null);
        }

        var playerIndex = random.NextInt(allySpawnPoints.Count);

        var player = allySpawnPoints[playerIndex];

        var enemyIndex = random.NextInt(enemySpawnPoints.Count);

        var enemy = enemySpawnPoints[enemyIndex];

        var positionOld = player.transform.position;

        var enemyAttackPanel = enemy.transform.Find("AttackPanel").gameObject;

        yield return(player.transform.DOMove(enemyAttackPanel.transform.position, 0.3f).WaitForCompletion());

        yield return(player.Attack());

        enemies[enemyIndex].health -= 10;

        yield return(player.transform.DOMove(positionOld, 0.3f).WaitForCompletion());

        isPlayerTurn = false;
    }
Esempio n. 2
0
        void Spawn()
        {
            if (prefab == Entity.Null)
            {
                return;
            }

            var random = new Unity.Mathematics.Random((uint)new System.Random().Next());

            var entities = new NativeArray <Entity>(spawnCount, Allocator.Temp);

            entityManager.Instantiate(prefab, entities);

            for (var i = 0; i < entities.Length; ++i)
            {
                entityManager.AddComponentData(entities[i], new Translation
                {
                    Value = new float3(
                        random.NextInt(-25, 25),
                        2,
                        random.NextInt(-25, 25)
                        )
                });
            }

            entities.Dispose();
        }
Esempio n. 3
0
        protected override void OnUpdate(EntityCommandBuffer.Concurrent ecb)
        {
            var random            = new Random(mainRandom.NextUInt(uint.MinValue, uint.MaxValue));
            var minSpeed          = setup.minSpeed;
            var maxSpeed          = setup.maxSpeed;
            var movementEnumCount = MovementEnumCount;

            Entities
            .WithAll <EnemyTag>()
            .WithNone <MovementTypeTag>()
            .ForEach((Entity entity, int entityInQueryIndex, ref Rotation rot) =>
            {
                ecb.AddComponent <MovementTypeTag>(entityInQueryIndex, entity);
                var i     = random.NextInt(0, 1) * 2 - 1; // -1 or 1
                rot.Value = quaternion.Euler(0, i * math.PI / 2, 0);

                var index = (MovementEnum)random.NextInt(0, movementEnumCount);
                index     = MovementEnum.Spiral;
                switch (index)
                {
                case MovementEnum.Linear:
                    break;

                case MovementEnum.Spiral:
                    ecb.AddComponent(entityInQueryIndex, entity, new MovementSpiral
                    {
                        speed = random.NextFloat(minSpeed, maxSpeed)
                    });
                    break;
                }
            })
            .ScheduleParallel();
        }
Esempio n. 4
0
    private void FixedUpdate()
    {
        var rnd = _rnd.NextInt(0, 5) > 3;

        Debug.Log(rnd);
        if (_jump)
        {
            ProcessJump();
            _jump = false;
        }

        if (_fire)
        {
            try
            {
                FireProjectile(_direction);
            }
            finally
            {
                _fire = false;
            }
        }

        ProcessMove();
    }
Esempio n. 5
0
            public int GetSpawnVehicleIndex(ref Unity.Mathematics.Random random, uint poolSpawn)
            {
                if (poolSpawn == 0)
                {
                    return(random.NextInt(0, VehiclePool.Length));
                }

                // Otherwise we need to figure out which vehicle to assign
                // Todo: could bake the num set bits out!
                uint pool       = poolSpawn;
                uint numSetBits = poolSpawn - ((poolSpawn >> 1) & 0x55555555);

                numSetBits = (numSetBits & 0x33333333) + ((numSetBits >> 2) & 0x33333333);
                numSetBits = ((numSetBits + (numSetBits >> 4) & 0x0F0F0F0F) * 0x01010101) >> 24;

                // we now have a number between 0 & 32,
                int  chosenBitIdx = random.NextInt(0, (int)numSetBits) + 1;
                uint poolTemp     = poolSpawn;
                uint lsb          = poolTemp;

                //TODO: make the below better?
                while (chosenBitIdx > 0)
                {
                    lsb       = poolTemp;
                    poolTemp &= poolTemp - 1;    // clear least significant set bit
                    lsb      ^= poolTemp;        // lsb contains the index (1<<index) of the pool for this position
                    chosenBitIdx--;
                }

                float fidx = math.log2(lsb);

                return((int)(fidx));
            }
        protected override void OnUpdate()
        {
            foreach (Pool entity in GetEntities <Pool>())
            {
                List <GameObject> activeArtifacts  = entity.artifactsPoolComponent.activePool;
                List <GameObject> passiveArtifacts = entity.artifactsPoolComponent.passivePool;
                int               passiveCount     = entity.artifactsPoolComponent.passiveCount;
                int               activeCount      = entity.artifactsPoolComponent.activeCount;
                Random            random           = Rand.GetRandom();
                List <GameObject> active           = new List <GameObject>();
                List <GameObject> passive          = new List <GameObject>();

                for (byte i = 0; i < passiveCount; i++)
                {
                    int        randId     = random.NextInt(passiveArtifacts.Count);
                    GameObject gameObject = GameObject.Instantiate(passiveArtifacts[randId]);
                    passiveArtifacts.RemoveAt(randId);
                    gameObject.GetComponent <ArtifactComponent>().id = i;
                    passive.Add(gameObject);
                }

                for (byte i = 0; i < activeCount; i++)
                {
                    int        randId     = random.NextInt(activeArtifacts.Count);
                    GameObject gameObject = GameObject.Instantiate(activeArtifacts[randId]);
                    activeArtifacts.RemoveAt(randId);
                    gameObject.GetComponent <ArtifactComponent>().id = i;
                    active.Add(gameObject);
                }

                entity.artifactsPoolComponent.active  = active;
                entity.artifactsPoolComponent.passive = passive;
            }
            Enabled = false;
        }
        static int2 RandomPointInRoom(ref Random rand, IntRect room)
        {
            int x = rand.NextInt(room.xMin, room.xMax + 1);
            int y = rand.NextInt(room.yMin, room.yMax + 1);

            return(new int2(x, y));
        }
Esempio n. 8
0
    IEnumerator SpawnZombieBatch()
    {
        while (spawnedCount < 5000)
        {
            yield return(new WaitForSeconds(4));

            spawnedCount += 80;
            Unity.Mathematics.Random rand = new Unity.Mathematics.Random(42);
            var  prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(zombiePrefab, World.DefaultGameObjectInjectionWorld);
            var  entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
            uint count         = 0;
            while (count++ < 100)
            {
                var instance = entityManager.Instantiate(prefab);
                var space    = rand.NextInt2(minPos, maxPos);
                space.x += rand.NextInt(-2, 2);
                space.y += rand.NextInt(-2, 2);
                var position = transform.TransformPoint(new float3(space.x, 1, space.y));
                entityManager.SetComponentData(instance, new Translation {
                    Value = position
                });
                var movementData = entityManager.GetComponentData <MovementComponent>(instance);
                movementData.speed += rand.NextFloat(-4f, 0f);
                entityManager.SetComponentData(instance, movementData);
            }
        }
    }
        private void InitializeRandomStats(int currentLevel, ref Unity.Mathematics.Random random,
                                           ref HealthStatComponent healthStatComponent,
                                           ref AttackStatComponent attackStatComponent,
                                           ref DefenceStatComponent defenceStatComponent,
                                           ref MagicStatComponent magicStatComponent)
        {
            var points = random.NextInt(currentLevel, currentLevel * 2);

            for (var i = 1; i < points; i++)
            {
                var randomStat = random.NextInt(0, 100);
                if (randomStat < 25)
                {
                    healthStatComponent.PointsSpent++;
                }
                else if (randomStat < 50)
                {
                    attackStatComponent.PointsSpent++;
                }
                else if (randomStat < 75)
                {
                    defenceStatComponent.PointsSpent++;
                }
                else if (randomStat < 100)
                {
                    magicStatComponent.PointsSpent++;
                }
            }
        }
        public unsafe void TestMeshColliderCreateWithInvalidIndices()
        {
            int numTriangles = 10;
            var vertices     = new NativeArray <float3>(numTriangles * 3, Allocator.Persistent);
            var triangles    = new NativeArray <int>(numTriangles * 3, Allocator.Persistent);

            for (int i = 0; i < numTriangles * 3; i++)
            {
                vertices[i]  = new float3((float)i, 1.0f * (float)(i % 2), (float)(i + 1));
                triangles[i] = i;
            }

            Random rnd = new Random(0x12345678);

            for (int i = 0; i < 100; i++)
            {
                int indexToChange = rnd.NextInt(0, triangles.Length - 1);

                int invalidValue = rnd.NextInt() * (rnd.NextBool() ? -1 : 1);
                triangles[indexToChange] = invalidValue;

                TestUtils.ThrowsException <System.ArgumentException>(
                    () => Unity.Physics.MeshCollider.Create(vertices, triangles)
                    );

                triangles[indexToChange] = indexToChange;
            }


            triangles.Dispose();
            vertices.Dispose();
        }
        public static void ANDNOT_1Byte()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            for (int i = 0; i < 3; i++)
            {
                byte operand = (byte)rng.NextInt(byte.MinValue + 1, byte.MaxValue + 1);

                NativeArray <byte> test = new NativeArray <byte>(rng.NextInt(1, 1_000_000), Allocator.Persistent);

                for (int j = 0; j < test.Length; j++)
                {
                    test[j] = (byte)rng.NextUInt();
                }

                ulong scalar = 0;

                for (int j = 0; j < test.Length; j++)
                {
                    scalar += (ulong)math.countbits(0x0000_00FF & (~(uint)test[j] & operand));
                }

                Assert.AreEqual(scalar, test.SIMD_CountBits(BitwiseOperation.ANDNOT, operand));

                test.Dispose();
            }
        }
Esempio n. 12
0
    protected override void OnUpdate()
    {
        gird = PathFindingSetup.Instance.pathfindingGrid;
        Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> pathPositionBuff, ref Translation translation, ref PathFollow pathFollow) =>
        {
            if (pathFollow.index >= 0)
            {
                var pathPosition = pathPositionBuff[pathFollow.index].Position;

                var targetPosition = new float3(pathPosition.x, pathPosition.y, 0);

                if (math.distance(targetPosition, translation.Value) < .1f)
                {
                    //next way point
                    pathFollow.index--;
                    return;
                }
                var moveDir = math.normalize(targetPosition - translation.Value);

                translation.Value += moveDir * _moveSpeed * Time.DeltaTime;
            }
            else if (pathFollow.index == -1)
            {
                //just finish last move
                pathFollow.index = -2;
                gird.GetXY(translation.Value, out var startX, out var startY);
                EntityManager.AddComponentData(entity, new PathFindingParam
                {
                    startPos = new int2(startX, startY),
                    endPos   = new int2(random.NextInt(0, 30), random.NextInt(0, 15)),
                });
            }
        });
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        int    mapWidth       = PathfindingGridSetup.Instance.pathfindingGrid.GetWidth();
        int    mapHeight      = PathfindingGridSetup.Instance.pathfindingGrid.GetHeight();
        float3 originPosition = float3.zero;
        float  cellSize       = PathfindingGridSetup.Instance.pathfindingGrid.GetCellSize();

        Unity.Mathematics.Random random = new Unity.Mathematics.Random(this.random.NextUInt(1, 10000));

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

        JobHandle jobHandle = Entities.WithNone <PathfindingParams>().ForEach((Entity entity, int entityInQueryIndex, in PathFollow pathFollow, in Translation translation) => {
            if (pathFollow.pathIndex == -1)
            {
                GetXY(translation.Value + new float3(1, 1, 0) * cellSize * +.5f, originPosition, cellSize, out int startX, out int startY);

                ValidateGridPosition(ref startX, ref startY, mapWidth, mapHeight);

                int endX = random.NextInt(0, mapWidth);
                int endY = random.NextInt(0, mapHeight);

                entityCommandBuffer.AddComponent(entityInQueryIndex, entity, new PathfindingParams
                {
                    startPosition = new int2(startX, startY), endPosition = new int2(endX, endY)
                });
            }
        }).Schedule(inputDeps);
Esempio n. 14
0
        void Start()
        {
            random_.InitState(1234);
            int  spawnnum = SceneManager.Num;
            bool first    = true;

            while (spawnnum > 0)
            {
                var num    = random_.NextInt(3, 5);
                var center = new float3(random_.NextFloat(-200, 200), 64f, random_.NextFloat(-200, 200));
                var replay_index_center = random_.NextInt(100, 10000);
                for (var j = 0; j < num; ++j)
                {
                    var pos          = center + random_.NextFloat3(-6, 6);
                    var replay_index = replay_index_center + random_.NextInt(20, 40) * (random_.NextBool() ? 1 : -1);
                    var entity       = FighterSystem.Instantiate(FighterManager.Prefab,
                                                                 pos,
                                                                 quaternion.identity,
                                                                 replay_index);
                    if (first)
                    {
                        var fighterSystem = World.DefaultGameObjectInjectionWorld.GetOrCreateSystem <FighterSystem>();
                        fighterSystem.PrimaryEntity = entity;
                        first = false;
                    }
                    --spawnnum;
                    if (spawnnum > 0)
                    {
                        continue;
                    }
                    break;
                }
            }
        }
Esempio n. 15
0
        public void Execute()
        {
            var random = new Random();

            random.InitState(Seed);

            var holeCount = (int)(Generator.SizeX * Generator.SizeY * 0.05f);

            for (int i = 0; i < holeCount; ++i)
            {
                var coord = new int2(random.NextInt(Generator.SizeX), random.NextInt(Generator.SizeY));

                // Do not spawn holes in the 4 corners
                if ((coord.x == 0 && coord.y == 0) ||
                    (coord.x == 0 && coord.y == Generator.SizeY - 1) ||
                    (coord.x == Generator.SizeX - 1 && coord.y == 0) ||
                    (coord.x == Generator.SizeX - 1 && coord.y == Generator.SizeY - 1))
                {
                    continue;
                }

                // Do not place holes under homebases
                if (HomebaseMap.ContainsKey(coord))
                {
                    continue;
                }

                if (FloorMap.ContainsKey(coord))
                {
                    CommandBuffer.DestroyEntity(FloorMap[coord]);
                    FloorMap.Remove(coord);
                }
            }
        }
Esempio n. 16
0
    protected override void OnUpdate()
    {
        var cursorsToInit = m_Cursors.CalculateEntityCount();

        if (cursorsToInit <= 0)
        {
            return;
        }

        var boardCount = m_BoardQuery.CalculateEntityCount();

        if (boardCount <= 0)
        {
            return;
        }

        var board  = m_BoardQuery.GetSingleton <LbBoard>();
        var random = new Unity.Mathematics.Random();

        random.InitState(1);

        Entities.ForEach((Entity entity, ref LbCursorInit ci, ref LbMovementTarget movement, ref LbDistanceToTarget distance) =>
        {
            var position   = new float3(random.NextInt(0, board.SizeX), 1, random.NextInt(0, board.SizeY));
            movement.To    = position;
            distance.Value = 0.0f;

            World.EntityManager.RemoveComponent <LbCursorInit>(entity);
        });
    }
        public static void ORNOT_4Bytes()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            for (int i = 0; i < 3; i++)
            {
                uint operand = (uint)rng.NextInt();

                NativeArray <uint> test = new NativeArray <uint>(rng.NextInt(1, 1_000_000), Allocator.Persistent);

                for (int j = 0; j < test.Length; j++)
                {
                    test[j] = (uint)rng.NextUInt();
                }

                ulong scalar = 0;

                for (int j = 0; j < test.Length; j++)
                {
                    scalar += (ulong)math.countbits((~(uint)test[j] | operand));
                }

                Assert.AreEqual(scalar, test.SIMD_CountBits(BitwiseOperation.ORNOT, operand));

                test.Dispose();
            }
        }
        public static void XNOR_2Bytes()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            for (int i = 0; i < 3; i++)
            {
                ushort operand = (ushort)rng.NextInt(ushort.MinValue + 1, ushort.MaxValue + 1);

                NativeArray <ushort> test = new NativeArray <ushort>(rng.NextInt(1, 1_000_000), Allocator.Persistent);

                for (int j = 0; j < test.Length; j++)
                {
                    test[j] = (ushort)rng.NextUInt();
                }

                ulong scalar = 0;

                for (int j = 0; j < test.Length; j++)
                {
                    scalar += (ulong)math.countbits(0x0000_FFFF & ~((uint)(test[j] ^ operand)));
                }

                Assert.AreEqual(scalar, test.SIMD_CountBits(BitwiseOperation.XNOR, operand));

                test.Dispose();
            }
        }
Esempio n. 19
0
        void generateRandomMotion(ref Random rnd, out MotionVelocity velocity, out MotionData motion, bool allowInfiniteMass)
        {
            motion = new MotionData
            {
                WorldFromMotion = generateRandomTransform(ref rnd),
                BodyFromMotion  = generateRandomTransform(ref rnd)
            };

            float3 inertia = rnd.NextFloat3(1e-3f, 100.0f);

            switch (rnd.NextInt(3))
            {
            case 0:     // all values random
                break;

            case 1:     // two values the same
                int index = rnd.NextInt(3);
                inertia[(index + 1) % 2] = inertia[index];
                break;

            case 2:     // all values the same
                inertia = inertia.zzz;
                break;
            }

            velocity = new MotionVelocity
            {
                LinearVelocity        = rnd.NextBool() ? float3.zero : rnd.NextFloat3(-50.0f, 50.0f),
                AngularVelocity       = rnd.NextBool() ? float3.zero : rnd.NextFloat3(-50.0f, 50.0f),
                InverseInertiaAndMass = (allowInfiniteMass && rnd.NextBool()) ? float4.zero : new float4(1.0f / inertia, rnd.NextFloat(1e-3f, 100.0f))
            };
        }
Esempio n. 20
0
        public void Execute()
        {
            PlaceSpawner(ref CommandBuffer, Generator.Player1Cursor, int2.zero);
            PlaceSpawner(ref CommandBuffer, Generator.Player2Cursor, int2.zero);
            PlaceSpawner(ref CommandBuffer, Generator.Player3Cursor, int2.zero);
            PlaceSpawner(ref CommandBuffer, Generator.Player4Cursor, int2.zero);

            var spawnLocation1 = new int2(0, 0);
            var spawnLocation2 = new int2(Generator.SizeX - 1, 0);
            var spawnLocation3 = new int2(0, Generator.SizeY - 1);
            var spawnLocation4 = new int2(Generator.SizeX - 1, Generator.SizeY - 1);

            PlaceSpawner(ref CommandBuffer, Generator.SpawnerPrefab, spawnLocation1);
            PlaceSpawner(ref CommandBuffer, Generator.SpawnerPrefab, spawnLocation2);
            PlaceSpawner(ref CommandBuffer, Generator.SpawnerPrefab, spawnLocation3);
            PlaceSpawner(ref CommandBuffer, Generator.SpawnerPrefab, spawnLocation4);

            var random = new Random();

            random.InitState(Seed);

            var checkFlag = kHoleFlag | kHomebaseFlag;

            var spawnerMap = new NativeHashMap <int2, byte>(Generator.AdditionalSpawners + 4, Allocator.Temp);

            spawnerMap.TryAdd(spawnLocation1, 1);
            spawnerMap.TryAdd(spawnLocation2, 1);
            spawnerMap.TryAdd(spawnLocation3, 1);
            spawnerMap.TryAdd(spawnLocation4, 1);

            var remaining = Generator.AdditionalSpawners;

            while (remaining > 0)
            {
                var coord = new int2(random.NextInt(Generator.SizeX), random.NextInt(Generator.SizeY));
                var index = coord.y * Generator.SizeY + coord.x;

                // Avoid placing spawners in holes, homebases and on top of other spawners
                var cellMapValue = DirectionBuffer[index].Value & checkFlag;
                if (cellMapValue == kHoleFlag || cellMapValue == kHomebaseFlag || spawnerMap.ContainsKey(coord))
                {
                    continue;
                }

                PlaceSpawner(ref CommandBuffer, Generator.SpawnerPrefab, coord);
                spawnerMap.TryAdd(coord, 1);
                remaining--;
            }

            spawnerMap.Dispose();

            var entity = CommandBuffer.CreateEntity();

            CommandBuffer.AddComponent(entity, new LbGameTimer()
            {
                Value = LbConstants.GameTime
            });
        }
Esempio n. 21
0
        public void Execute(Entity entity, int index, ref LbArrowPosition arrowPosition, [ReadOnly] ref LbPlayer player)
        {
            var random   = new Random((uint)(Seed + index));
            var position = new float3(random.NextInt(0, Size), 1, random.NextInt(0, Size));

            arrowPosition.Value = position;

            CommandBuffer.SetComponent(index, entity, arrowPosition);
            CommandBuffer.RemoveComponent <LbArrow>(index, entity);
        }
            // public int i_eliteScore ;


            public void Execute(int i)
            {
                int i_eliteProbablityCount = na_indexProbability.Length;

                random.InitState((uint)(random.NextInt(i_eliteProbablityCount) + na_randomValues [i]));
                random.NextInt2();

                int i_firstPorbabilityIndex  = random.NextInt(0, i_eliteProbablityCount);
                int i_secondPorbabilityIndex = random.NextInt(0, i_eliteProbablityCount);

                int i_firstParentEntityIndex  = na_indexProbability [i_firstPorbabilityIndex];
                int i_secondParentEntityIndex = na_indexProbability [i_secondPorbabilityIndex];



                Entity firstParentEntity  = na_parentPopulationEntities [i_firstParentEntityIndex];
                Entity secondParentEntity = na_parentPopulationEntities [i_secondParentEntityIndex];

                DynamicBuffer <NNInput2HiddenLayersWeightsBuffer>  a_firstParentInput2HiddenLayersWeights  = input2HiddenLayersWeightsBuffer [firstParentEntity];
                DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_firstParentHidden2OutputLayersWeights = hidden2OutputLayersWeightsBuffer [firstParentEntity];

                DynamicBuffer <NNInput2HiddenLayersWeightsBuffer>  a_secondParentInput2HiddenLayersWeights  = input2HiddenLayersWeightsBuffer [secondParentEntity];
                DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_secondParentHidden2OutputLayersWeights = hidden2OutputLayersWeightsBuffer [secondParentEntity];

                Entity offspringEntity = na_offspringPopulationEntities [i];

                DynamicBuffer <NNInput2HiddenLayersWeightsBuffer>  a_offspringInput2HiddenLayersWeights   = input2HiddenLayersWeightsBuffer [offspringEntity];
                DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_offspringtHidden2OutputLayersWeights = hidden2OutputLayersWeightsBuffer [offspringEntity];


                int i_input2HiddenLayersWeightsCount  = a_firstParentInput2HiddenLayersWeights.Length;
                int i_hidden2OutputLayersWeightsCount = a_firstParentHidden2OutputLayersWeights.Length;

                a_offspringInput2HiddenLayersWeights.ResizeUninitialized(i_input2HiddenLayersWeightsCount);
                a_offspringtHidden2OutputLayersWeights.ResizeUninitialized(i_hidden2OutputLayersWeightsCount);

                // 50 / 50 chance to get trait (NN weights) from parent A or B.
                for (int j = 0; j < a_offspringInput2HiddenLayersWeights.Length; j++)
                {
                    float f = random.NextFloat() < 0.5f ? a_firstParentInput2HiddenLayersWeights [j].f : a_secondParentInput2HiddenLayersWeights [j].f;
                    a_offspringInput2HiddenLayersWeights [j] = new NNInput2HiddenLayersWeightsBuffer()
                    {
                        f = f
                    };
                }

                for (int j = 0; j < a_offspringtHidden2OutputLayersWeights.Length; j++)
                {
                    float f = random.NextFloat() < 0.5f ? a_firstParentHidden2OutputLayersWeights [j].f : a_secondParentHidden2OutputLayersWeights [j].f;
                    a_offspringtHidden2OutputLayersWeights [j] = new NNHidden2OutputLayersWeightsBuffer()
                    {
                        f = f
                    };
                }
            }
            Entity RandomCreateVoxel(int jobIndex, Prefabs prefabs, int y, float height)
            {
                if (y + 1 > height)
                {
                    var randomFactroy = Random.NextInt(0, 39);
                    if (randomFactroy < 10)
                    {
                        return(CommandBuffer.Instantiate(jobIndex, prefabs.GroundGreen));
                    }
                    if (randomFactroy < 20)
                    {
                        return(CommandBuffer.Instantiate(jobIndex, prefabs.GroundBrown));
                    }
                    if (randomFactroy < 30)
                    {
                        return(CommandBuffer.Instantiate(jobIndex, prefabs.GreyStone));
                    }
                    // if (randomFactroy < 40)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.Ground3);
                    // if (randomFactroy < 50)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.Ground4);
                    // if (randomFactroy < 60)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.Ground5);
                    // if (randomFactroy < 70)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.GroundVegetation0);
                    // if (randomFactroy < 80)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.GroundVegetation1);
                    // if (randomFactroy < 90)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.GroundVegetation2);
                    // if (randomFactroy < 100)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.GroundVegetation3);
                    // if (randomFactroy < 110)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.GroundVegetation4);
                    // if (randomFactroy < 120)
                    //     return CommandBuffer.Instantiate (jobIndex, prefabs.GroundVegetation5);
                }
                if (y >= 0)
                {
                    var randomFactroy = Random.NextInt(0, 39);
                    if (randomFactroy < 10)
                    {
                        return(CommandBuffer.Instantiate(jobIndex, prefabs.GroundBrown));
                    }
                    if (randomFactroy < 20)
                    {
                        return(CommandBuffer.Instantiate(jobIndex, prefabs.Sand));
                    }
                    if (randomFactroy < 30)
                    {
                        return(CommandBuffer.Instantiate(jobIndex, prefabs.GreyStone));
                    }
                }

                return(CommandBuffer.Instantiate(jobIndex, prefabs.GroundBrown));
            }
Esempio n. 24
0
 void TargetHit(float3 position)
 {
     if (zoomedForVertices)
     {
         GameObject.Instantiate(hitsSmall[_rand.NextInt(0, hitsSmall.Length)], position, quaternion.identity);
     }
     else
     {
         GameObject.Instantiate(hitsLarge[_rand.NextInt(0, hitsLarge.Length)], position, quaternion.identity);
     }
 }
Esempio n. 25
0
    private IEnumerator EnemyTurn(bool isMonster)
    {
        // Special case for the Lancelot battle.
        if (_activeEnemy.damage == 0)
        {
            yield break;
        }

        var positionPrev = _activeEnemy.transform.position;

        GameObject targetPlayer;

        if (GameState.Instance.ArthurHasExcalibur)
        {
            targetPlayer = _players.First();
        }
        else
        {
            targetPlayer = _players[_random.NextInt(0, _players.Count)];
        }

        var animator = _activeEnemy.GetComponent <Animator>();

        animator.SetBool(_aidIsMoving, false);
        animator.SetBool(_aidIsAttacking, true);

        yield return(_activeEnemy.transform.DOMove(targetPlayer.transform.position, Constants.SpeedAttack).SetSpeedBased().WaitForCompletion());

        if (isMonster)
        {
            audioSourceSound.clip = audioClipHitMonster;
        }
        else
        {
            audioSourceSound.clip = audioClipHitBoss;
        }

        audioSourceSound.Play();

        if (targetPlayer == _players[0])
        {
            GameState.Instance.DamageArthur(_activeEnemy.damage);
        }
        else
        {
            GameState.Instance.DamageLancelot(_activeEnemy.damage);
        }

        yield return(_activeEnemy.transform.DOMove(positionPrev, Constants.SpeedAttack).SetSpeedBased().WaitForCompletion());

        animator.SetBool(_aidIsAttacking, false);
    }
Esempio n. 26
0
        static void GenerateRooms(DynamicBuffer <MapTiles> map, MapData mapData, GenerateMap genData, DynamicBuffer <IntRect> rooms)
        {
            Random rand = new Random((uint)genData.seed);

            for (int i = 0; i < genData.iterationCount; ++i)
            {
                int     w       = rand.NextInt(genData.minRoomSize, genData.maxRoomSize);
                int     h       = rand.NextInt(genData.minRoomSize, genData.maxRoomSize);
                int     x       = rand.NextInt(1, mapData.width - w - 1);
                int     y       = rand.NextInt(1, mapData.height - h - 1);
                IntRect newRoom = IntRect.FromPositionSize(x, y, w, h);

                bool ok = true;

                for (int roomIndex = 0; roomIndex < rooms.Length; ++roomIndex)
                {
                    var existing = rooms[roomIndex];

                    // Accounting for walls during overlap test
                    existing.Size += 2;
                    existing.Position--;
                    if (newRoom.Intersect(existing))
                    {
                        ok = false;
                        break;
                    }
                }

                if (ok)
                {
                    BuildRoom(map, mapData, newRoom);

                    if (rooms.Length > 0)
                    {
                        var newPos  = newRoom.Center;
                        var prevPos = rooms[rooms.Length - 1].Center;
                        if (rand.NextInt(0, 2) == 1)
                        {
                            BuildHorizontalTunnel(map, mapData, prevPos.x, newPos.x, prevPos.y);
                            BuildVerticalTunnel(map, mapData, prevPos.y, newPos.y, newPos.x);
                        }
                        else
                        {
                            BuildVerticalTunnel(map, mapData, prevPos.y, newPos.y, prevPos.x);
                            BuildHorizontalTunnel(map, mapData, prevPos.x, newPos.x, newPos.y);
                        }
                    }

                    rooms.Add(newRoom);
                }
            }
        }
Esempio n. 27
0
        protected override void OnUpdate()
        {
            if (UnityEngine.Time.time - m_LastSpawn < m_SpawnRate)
            {
                return;
            }

            m_LastSpawn = UnityEngine.Time.time - m_Random.NextFloat(-GameData.Instance.spawnRateNoise, GameData.Instance.spawnRateNoise);

            int batchCount = m_Random.NextInt(GameData.Instance.enemySpawnBatchCountMin, GameData.Instance.enemySpawnBatchCountMax);

            for (int i = 0; i < batchCount; i++)
            {
                var instanceSpawnPos = FirstWaypointPos +
                                       new float3(m_Random.NextFloat(-GameData.Instance.spawnPositionNoise, GameData.Instance.spawnPositionNoise),
                                                  0, m_Random.NextFloat(-GameData.Instance.spawnPositionNoise, GameData.Instance.spawnPositionNoise));

                Entity prefab   = GameData.Instance.EnemyEntityPrefab;
                Entity instance = EntityManager.Instantiate(prefab);
                EntityManager.SetName(instance, "Enemy");
                EntityManager.AddComponentData(instance, new AgentTag {
                });

                EntityManager.SetComponentData(instance, new Translation {
                    Value = instanceSpawnPos
                });
                EntityManager.AddComponentData(instance, new MoveSpeedComponent {
                    Value = GameData.Instance.agentMoveSpeed
                });

                EntityManager.AddComponentData(instance, new FollowWaypointTag {
                });
                EntityManager.AddComponentData(instance, new WaypointMovementComponent {
                    CurrentTargetIndex = 0
                });

                EntityManager.AddComponentData(instance, new AttackRadiusComponent {
                    Value = GameData.Instance.agentScanRadius
                });

                EntityManager.AddSharedComponentData(instance, new EnemyTeamComponent());

                int maxHealth = m_Random.NextInt(GameData.Instance.agentInitialHealthMin, GameData.Instance.agentInitialHealthMax);
                EntityManager.AddComponentData(instance, new HealthComponent {
                    Health = maxHealth, MaxHealth = maxHealth
                });
                EntityManager.AddComponentData(instance, new AttackStatusComponent {
                });
            }

            StatDisplay.Instance.AgentCount += batchCount;
        }
Esempio n. 28
0
        public void PathRandomObstacles()
        {
            using (var grid = new TestGrid(31))
            {
                int obstacleCount = 32;
                var rand          = new Unity.Mathematics.Random(0xF545AA3F);
                for (int i = 0; i < obstacleCount; i++)
                {
                    var faceIndex      = rand.NextInt(0, 6);
                    var xy             = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)xy.x, y = (short)xy.y
                    };
                    var cubeFace = new CartesianGridOnCubeFace {
                        Value = (byte)faceIndex
                    };
                    var cellIndex = CartesianGridOnCubeUtility.CellIndex(sourcePosition, cubeFace, grid.RowCount);
                    if (rand.NextBool())
                    {
                        grid.AddWallWest(cellIndex);
                    }
                    else
                    {
                        grid.AddWallSouth(cellIndex);
                    }
                }

                int testCount = 64;
                for (int i = 0; i < testCount; i++)
                {
                    var sourceXY        = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var sourceFaceIndex = rand.NextInt(0, 6);
                    var sourceCubeFace  = new CartesianGridOnCubeFace {
                        Value = (byte)sourceFaceIndex
                    };
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)sourceXY.x, y = (short)sourceXY.y
                    };

                    var targetXY        = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var targetFaceIndex = rand.NextInt(0, 6);
                    var targetCubeFace  = new CartesianGridOnCubeFace {
                        Value = (byte)targetFaceIndex
                    };
                    var targetPosition = new CartesianGridCoordinates {
                        x = (short)targetXY.x, y = (short)targetXY.y
                    };

                    grid.WalkPathDistance(sourcePosition, sourceCubeFace, targetPosition, targetCubeFace);
                }
            }
        }
Esempio n. 29
0
    private static void FullUpdate(ref Translation position, ref Rotation rotation, ref BoidData boid, NativeArray <BoidData> boidsData,
                                   float agentNeighbourDistance, float agentAvoidDistance, float3 goalPos, float deltaTime,
                                   float minSpeed, float maxSpeed, Bounds bounds, uint baseSeed, float avoidCollidersDistance, PhysicsWorld world)
    {
        float3 direction = float3.zero;
        float3 forward   = math.forward(rotation.Value);
        bool   turning;

        RaycastInput rayInput = new RaycastInput
        {
            Start  = boid.CurrentPosition,
            End    = boid.CurrentPosition + avoidCollidersDistance * forward,
            Filter = CollisionFilter.Default
        };

        if (!bounds.Contains(boid.CurrentPosition)) //handle getting out of bounds
        {
            turning   = true;
            direction = (float3)bounds.center - boid.CurrentPosition;
        }
        else if (world.CastRay(rayInput, out Unity.Physics.RaycastHit hit))
        {
            turning   = true;
            direction = (float3)Vector3.Reflect(forward, hit.SurfaceNormal);
        }
        else
        {
            turning = false;
        }

        if (turning) //adjust path if needed
        {
            rotation.Value = math.slerp(rotation.Value, quaternion.LookRotation(direction, new float3(0, 1, 0)), boid.RotationSpeed * deltaTime);
        }
        else //random direction or direction calculated based on the flocking rules
        {
            Unity.Mathematics.Random rand = new Unity.Mathematics.Random(baseSeed + boid.Index);

            if (rand.NextInt(0, 100) < 10)
            {
                boid.Speed = rand.NextFloat(minSpeed, maxSpeed);
            }
            if (rand.NextInt(0, 100) < 20)
            {
                ApplyBoidRules(ref boid, ref rotation, boidsData, agentNeighbourDistance, agentAvoidDistance, goalPos, deltaTime);
            }
        }

        //move agent forward, along its direction
        position.Value      += boid.Speed * math.forward(rotation.Value) * deltaTime;
        boid.CurrentPosition = position.Value;
    }
        void CreateObstacleEntities(GameObject obstaclePrefab, SimulationConfig config, NativeList <Entity> obstacles)
        {
            var gameConversionSettings = GameObjectConversionSettings.FromWorld(World, null);
            var entityPrefab           = GameObjectConversionUtility.ConvertGameObjectHierarchy(obstaclePrefab, gameConversionSettings);
            var random = new Random(config.Seed);

            var obstacleRings    = config.ObstacleRingsCount;
            var obstaclesPerRing = config.ObstaclesPerRing;
            var mapSize          = config.MapSize;

            var obstacleRadius = EntityManager.GetComponentData <Radius>(entityPrefab).Value;
            var scale          = new float3(2, 2, .1f) * obstacleRadius;

            obstacleRadius *= mapSize;

            for (var i = 1; i <= obstacleRings; i++)
            {
                var ringRadius    = (i / (obstacleRings + 1f)) * (mapSize * .5f);
                var circumference = ringRadius * 2f * math.PI;
                var maxCount      = (int)math.ceil(circumference / (2f * obstacleRadius) * 2f);
                var offset        = random.NextInt(0, maxCount);
                var holeCount     = random.NextInt(1, 3);

                for (int j = 0; j < maxCount; j++)
                {
                    var t = (float)j / maxCount;
                    if ((t * holeCount) % 1f < obstaclesPerRing)
                    {
                        var angle    = (j + offset) / (float)maxCount * (2f * Mathf.PI);
                        var position = new float3(mapSize * .5f + Mathf.Cos(angle) * ringRadius, mapSize * .5f + Mathf.Sin(angle) * ringRadius, 0);
                        // Debug.DrawRay(position / mapSize,-Vector3.forward * .05f,Color.green,10000f);
                        var obstacle = EntityManager.Instantiate(entityPrefab);
                        EntityManager.AddComponentData(obstacle, new Translation {
                            Value = position / mapSize
                        });
                        EntityManager.AddComponentData(obstacle, new NonUniformScale {
                            Value = scale
                        });
                        EntityManager.AddComponentData(obstacle, new ObstacleTag());

                        obstacles.Add(obstacle);

                    #if UNITY_EDITOR
                        EntityManager.SetName(obstacle, $"Obstacle:{obstacle.Index}");
                    #endif
                    }
                }
            }

            Enabled = false;
        }