Example #1
0
        private void SetCalculateBulletTrajectoryJob()
        {
            muzzleRotation[0]       = muzzleTransform.rotation;
            projectileDispersion[0] = dispersion;
            random[0] = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, 10000));


            CalculateProjectileTrajectoryJob job = new CalculateProjectileTrajectoryJob()
            {
                muzzleRotation       = this.muzzleRotation,
                projectileDispersion = this.projectileDispersion,
                random = this.random,
                projectileDirection = this.output
            };

            handler = job.Schedule(muzzleRotation.Length, 1);
        }
Example #2
0
        private static bool CheckNeighbourBlocks <T>(Random random,
                                                     int2 point,
                                                     int2 origin,
                                                     int2 size,
                                                     NativeHashMap <int2, Entity> map,
                                                     NativeList <int2> buffer,
                                                     ComponentDataFromEntity <T> filter,
                                                     NativeHashMap <int2, int> checkMap) where T : struct, IComponentData
        {
            int nextRandom = random.NextInt(0, 2);

            if (checkMap.ContainsKey(point))
            {
                return(false);
            }

            if (point.x >= size.x || point.y >= size.y || point.x < 0 || point.y < 0)
            {
                return(false);
            }

            if (!filter.HasComponent(map[point]) && !point.Equals(origin))
            {
                buffer.Add(point);
                return(true);
            }

            checkMap.Add(point, -1);

            if (nextRandom == 0)
            {
                CheckNeighbourBlocks(random, new int2(point.x + 1, point.y), origin, size, map, buffer, filter, checkMap);
                CheckNeighbourBlocks(random, new int2(point.x - 1, point.y), origin, size, map, buffer, filter, checkMap);
                CheckNeighbourBlocks(random, new int2(point.x, point.y + 1), origin, size, map, buffer, filter, checkMap);
                CheckNeighbourBlocks(random, new int2(point.x, point.y - 1), origin, size, map, buffer, filter, checkMap);
            }
            else
            {
                CheckNeighbourBlocks(random, new int2(point.x, point.y + 1), origin, size, map, buffer, filter, checkMap);
                CheckNeighbourBlocks(random, new int2(point.x, point.y - 1), origin, size, map, buffer, filter, checkMap);
                CheckNeighbourBlocks(random, new int2(point.x + 1, point.y), origin, size, map, buffer, filter, checkMap);
                CheckNeighbourBlocks(random, new int2(point.x - 1, point.y), origin, size, map, buffer, filter, checkMap);
            }

            return(false);
        }
Example #3
0
    private void InitializeEntity(ref Unity.Mathematics.Random random, EntityManager manager, Entity entity)
    {
        var       moves = manager.GetBuffer <DanceMove>(entity);
        DanceMove move  = default;

        for (uint i = 0; i < danceLoopLength; ++i)
        {
            var values = random.NextFloat4() * 10f - 5f;
            move.Duration = values.w + 5f;
            move.Velocity = values.xyz;
            random.state  = random.NextUInt();
            moves.Add(move);
        }
        manager.SetComponentData(entity, new Velocity {
            Value = (random.NextFloat3() - 0.5f) * 8f
        });
    }
Example #4
0
        private NativeArray <Vertex> InitializeVertexBuffer()
        {
            Vector3[]            normal  = sampleMesh.normals;
            Vector4[]            tangent = sampleMesh.tangents;
            NativeArray <Vertex> verts   = new NativeArray <Vertex>(normal.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
            Vertex *ptr  = verts.Ptr();
            int     seed = Guid.NewGuid().GetHashCode();
            Random  rand = new Random(*(uint *)UnsafeUtility.AddressOf(ref seed));

            for (int i = 0; i < verts.Length; ++i)
            {
                ref Vertex vert = ref ptr[i];
                vert.tangent  = normalize((Vector3)tangent[i]);
                vert.normal   = normalize(normal[i]);
                vert.p        = rand.NextUInt2();
                vert.binormal = normalize(cross(vert.normal, vert.tangent) * tangent[i].w);
            }
        /// <summary>
        /// Spawn a certain number of Entities;产生count个实体
        /// </summary>
        void SpawnSphere()
        {
            Entity  entity;
            Vector2 circle;

            Unity.Mathematics.Random random = new Unity.Mathematics.Random();
            random.InitState(10);

            for (int i = 0; i < spawnCount; i++)
            {
                entity = entityManager.Instantiate(sourceEntity);

                entityManager.SetComponentData(entity, new Translation {
                    Value = center + random.NextFloat3(-range, range)
                });
            }
        }
Example #6
0
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var extends     = int3(XExtends, YExtends, ZExtends);
        var translation = float3(transform.position);

        var entityManager = conversionSystem.DstEntityManager;

        var archetype = entityManager.CreateArchetype(ComponentType.ReadWrite <VoxelColor>(),
                                                      ComponentType.ReadWrite <Translation>(), ComponentType.ReadWrite <LocalToWorld>(),
                                                      ComponentType.ReadWrite <RandomVelocity>(), ComponentType.ReadWrite <Velocity>(),
                                                      ComponentType.ReadWrite <Scale>());
        var r = new Random();

        r.InitState();

        var array = new NativeArray <Entity>(extends.x * extends.y * extends.z, Allocator.Temp);

        entityManager.CreateEntity(archetype, array);

        for (int x = 0; x < extends.x; x++)
        {
            for (int z = 0; z < extends.z; z++)
            {
                for (int y = 0; y < extends.y; y++)
                {
                    var p = translation + (int3(x, y, z) * Spread);
                    var e = array[x + extends.y * (y + extends.z * z)];
                    entityManager.SetComponentData(e, new Translation {
                        Value = p
                    });
                    entityManager.SetComponentData(e,
                                                   new RandomVelocity {
                        Speed = r.NextFloat(0f, 5f), Random = new Random(r.NextUInt())
                    });
                    entityManager.SetComponentData(e, new Scale
                    {
                        Value = r.NextFloat(0.5f, 10)
                    });
                }
            }
        }

        entityManager.DestroyEntity(entity);
        array.Dispose();
    }
Example #7
0
        void GenerateExampleSystem()
        {
            var rangen = new Unity.Mathematics.Random(_seed);

            objects = new List <Particle>(2 * NumObjects);
            objects.Add(new Particle(new double3(0.0d, 0, 0d), new double3(0.0d, 0, 0), 1.0d));
            // objects.Add(new Particle(new double3(1e1d, 0d, 0d), new double3(0d, 0d, math.sqrt(G/10d)), 0.001d));
            // objects.Add(new Particle(new double3(1.02e1d, 0d, 0d), new double3(0d, 0d, math.sqrt(G/10d) + math.sqrt(G*.001/.2d)), 0.0002d));
            // objects.Add(new Particle(new double3(-1e1d, 0d, 0d), new double3(0d, 0d, -math.sqrt(G/10d)), 0.002d));
            // objects.Add(new Particle(new double3(0d, 0d, 1.2e1d), new double3(1d, 0d, 0d), 0.0001d));


            // Add some asteroids/debris
            while (objects.Count < NumObjects)
            {
                float  angle  = rangen.NextFloat(2f * math.PI);
                double length = (1 - math.pow(rangen.NextDouble(), 2)) * 15d + 5d;
                var    pos    = new double3(math.rotate(quaternion.RotateY(angle), new float3(1, 0, 0)))
                                * length;
                var vel = new double3(-pos.z, 0, pos.x) / length * math.sqrt(G / length);
                var m   = rangen.NextDouble(.0001d);
                var p   = new Particle(pos, vel, m);
                objects.Add(p);
            }
            NumObjects = objects.Count;


            // Shift gameObjects so COM and total momentum is 0
            var totalmass = 0d;
            var com       = new double3(0);
            var velocity  = new double3(0);

            for (int i = 0; i < NumObjects; i++)
            {
                totalmass += objects[i].mass;
                com       += objects[i].position * objects[i].mass;
                velocity  += objects[i].velocity * objects[i].mass;
            }
            com      /= totalmass;
            velocity /= totalmass;
            for (int i = 0; i < NumObjects; i++)
            {
                objects[i] -= new Particle(com, velocity, 0);
            }
        }
Example #8
0
    private void Start()
    {
        Unity.Mathematics.Random rand = new Unity.Mathematics.Random((uint)Time.realtimeSinceStartup);
        for (int i = 0; i < numberOfCube; i++)
        {
            GameObject           cube      = Instantiate(this.cube);
            RigidBody2DComponent bodyProxy = cube.GetComponent <RigidBody2DComponent>();
            RigidBody2D          body      = bodyProxy.Value;
            body.Mass     = rand.NextFloat(0.1f, 3f);
            body.Position = new float2(rand.NextFloat(-500f, 500f), rand.NextFloat(-500f, 500f));
            float angle = math.atan2(body.Position.y, body.Position.x) + math.PI * 0.5f;
            float speed = math.pow(math.length(body.Position), 2f / 3.5f);
            body.Velocity   = new float2(speed * math.cos(angle), speed * math.sin(angle));
            bodyProxy.Value = body;

            cube.transform.parent = transform;
        }
    }
        unsafe ComponentType[] CreateRandomMatchingQueryTypes(NativeArray <EntityArchetype> archetypes)
        {
            var random  = new Random(34343);
            var typeSet = new HashSet <ComponentType>();

            for (int i = 0; i < archetypes.Length; i++)
            {
                if (random.NextBool())
                {
                    for (int typeIndex = 0; typeIndex < archetypes[i].Archetype->TypesCount; typeIndex++)
                    {
                        typeSet.Add(archetypes[i].Archetype->Types[0].ToComponentType());
                    }
                }
            }

            return(typeSet.ToArray());
        }
Example #10
0
        void Start()
        {
            Unity.Mathematics.Random rand          = new Unity.Mathematics.Random(111);
            EntityManager            entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

            Entity prefabEntity = entityManager.CreateEntityQuery(typeof(PrefabEntityComponent)).GetSingleton <PrefabEntityComponent>().prefabEnity;

            for (int i = 0; i < playerNumber; i++)
            {
                var instance = entityManager.Instantiate(prefabEntity);
                entityManager.SetComponentData(instance, new Translation {
                    Value = new float3(rand.NextFloat(-5, 5), rand.NextFloat(-5, 5), 0)
                });
                entityManager.SetComponentData(instance, new MoveSpeedComponent {
                    value = rand.NextFloat(1, 3)
                });
            }
        }
Example #11
0
        public void PostConstruct()
        {
            _biomeDefs            = BiomeDefs.BiomeDefData;
            _terrainCurvesSampled = BiomeDefs.TerrainCurvesSampled;
            _lodes          = BiomeDefs.Lodes;
            _lodeThresholds = BiomeDefs.LodeThresholds;

            //generate octave offsets
            var random = new Random();

            random.InitState(928349238); // TODO fill with seed
            _offsets    = new NativeArray <float2>(GeometryConsts.MAX_OCTAVES, Allocator.Persistent);
            _offsets[0] = 0;
            for (var i = 1; i < GeometryConsts.MAX_OCTAVES; i++)
            {
                _offsets[i] = random.NextFloat2(-1f, 1f);
            }
        }
        public static void UInt()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            for (int i = 0; i < 3; i++)
            {
                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.NextInt();
                }

                Assert.AreEqual(Scalar(test.GetUnsafePtr(), sizeof(uint) * test.Length), test.SIMD_CountBits());

                test.Dispose();
            }
        }
Example #13
0
        public static void Long()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <long>(
                (array) =>
            {
                long x = long.MaxValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = math.min(x, array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Minimum());
            },
                () => (long)rng.NextInt() | ((long)rng.NextInt() << 32));
        }
Example #14
0
    private StartPatternStamp[] GeneratePatternStamps(int numberOfStamps, int2 gridSize, int2[][] stampPatterns)
    {
        StartPatternStamp[] stamps = new StartPatternStamp[numberOfStamps];
        var rng = new Unity.Mathematics.Random(WorldSeed);

        for (int idx = 0; idx < numberOfStamps; ++idx)
        {
            var randomStamp    = rng.NextInt(stampPatterns.Length);
            var randomLocation = rng.NextInt2(gridSize);
            stamps[idx] = new StartPatternStamp
            {
                pattern  = stampPatterns[randomStamp],
                location = randomLocation
            };
        }

        return(stamps);
    }
Example #15
0
        public static void SByte()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <sbyte>(
                (array) =>
            {
                sbyte x = sbyte.MinValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = (sbyte)math.max((int)x, (int)array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Maximum());
            },
                () => (sbyte)rng.NextInt(sbyte.MaxValue, sbyte.MaxValue + 1));
        }
Example #16
0
        public void Init(ref Random rand)
        {
            for (int i = 0; i < Octaves * 2; i++)
            {
                offsets[i] = rand.NextFloat();
            }

            float amp        = Gain;
            float ampFractal = 1f;

            for (int i = 0; i < Octaves; i++)
            {
                ampFractal += amp;
                amp        *= Gain;
            }

            fractalBounding = 1f / ampFractal;
        }
Example #17
0
        public static void UInt()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <uint>(
                (array) =>
            {
                uint x = uint.MinValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = math.max(x, array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Maximum());
            },
                rng.NextUInt);
        }
Example #18
0
        public static void ULong()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <ulong>(
                (array) =>
            {
                ulong x = ulong.MinValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = math.max(x, array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Maximum());
            },
                () => rng.NextUInt() | ((ulong)rng.NextUInt() << 32));
        }
Example #19
0
        public static void Double()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <double>(
                (array) =>
            {
                double x = double.NegativeInfinity;

                for (int j = 0; j < array.Length; j++)
                {
                    x = math.max(x, array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Maximum());
            },
                rng.NextDouble);
        }
Example #20
0
        public static void Short()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <short>(
                (array) =>
            {
                short x = short.MaxValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = (short)math.min((int)x, (int)array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Minimum());
            },
                () => (short)rng.NextInt(short.MinValue, short.MaxValue + 1));
        }
Example #21
0
    protected override void OnCreate()
    {
        var desc = new EntityQueryDesc()
        {
            None = new ComponentType[] { ComponentType.ReadOnly <LbDisabled>() },
            All  = new ComponentType [] { typeof(LbBoardGenerator) }
        };

        m_GeneratorQuery = GetEntityQuery(desc);

        m_FloorMap     = new NativeHashMap <int2, Entity>(1, Allocator.Persistent);
        m_WallMap      = new NativeHashMap <int2, byte>(1, Allocator.Persistent);
        m_HomebaseMap  = new NativeHashMap <int2, byte>(4, Allocator.Persistent);
        m_DirectionMap = new NativeList <short>(1, Allocator.Persistent);

        m_Barrier = World.GetOrCreateSystem <LbSimulationBarrier>();
        m_Random  = new Random(50);
    }
Example #22
0
        public static void Float()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <float>(
                (array) =>
            {
                float x = float.NegativeInfinity;

                for (int j = 0; j < array.Length; j++)
                {
                    x = math.max(x, array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Maximum());
            },
                rng.NextFloat);
        }
Example #23
0
        public static void Byte()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <byte>(
                (array) =>
            {
                byte x = byte.MaxValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = (byte)math.min((uint)x, (uint)array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Minimum());
            },
                () => (byte)rng.NextUInt(byte.MinValue, byte.MaxValue + 1));
        }
Example #24
0
        public static void UShort()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <ushort>(
                (array) =>
            {
                ushort x = ushort.MinValue;

                for (int j = 0; j < array.Length; j++)
                {
                    x = (ushort)math.max((uint)x, (uint)array[j]);
                }

                Assert.AreEqual(x, array.SIMD_Maximum());
            },
                () => (ushort)rng.NextUInt(ushort.MaxValue, ushort.MaxValue + 1));
        }
        public void Execute(int index)
        {
            var foregroundObjectBox = PlacedForegroundObjects[index];
            // See comment regarding Random in jobs in BackgroundGenerator.PlaceObjectsJob
            var rand = new Random(RandomSeed + (uint)index * ObjectPlacementUtilities.LargePrimeNumber);

            var prefabIndex = rand.NextInt(OccludingObjectBounds.Length);
            var bounds      = OccludingObjectBounds[prefabIndex];
            var foregroundObjectBoundingBox = ObjectPlacementUtilities.IntersectRect(
                foregroundObjectBox.BoundingBox, ImageCoordinates);

            //place over a foreground object such that overlap is between 10%-30%
            var numTries = 0;

            PlacedOccludingObjects[index] = new PlacedObject()
            {
                PrefabIndex = -1
            };
            while (numTries < 1000)
            {
                numTries++;
                var rotation = rand.NextQuaternionRotation();
                var position = new Vector3(rand.NextFloat(foregroundObjectBoundingBox.xMin, foregroundObjectBoundingBox.xMax),
                                           rand.NextFloat(foregroundObjectBoundingBox.yMin, foregroundObjectBoundingBox.yMax), 0f);
                var scale = ObjectPlacementUtilities.ComputeScaleToMatchArea(Transformer, position, rotation, bounds,
                                                                             rand.NextFloat(ScalingMin, ScalingMin + ScalingSize) * foregroundObjectBox.ProjectedArea);
                var placedObject = new PlacedObject()
                {
                    Scale       = scale,
                    Rotation    = rotation,
                    Position    = position,
                    PrefabIndex = prefabIndex
                };
                // NOTE: This computation is done with orthographic projection and will be slightly inaccurate
                //       when rendering with perspective projection
                var occludingObjectBox = GetBoundingBox(bounds, scale, position, rotation);
                var cropping           = ComputeOverlap(foregroundObjectBoundingBox, occludingObjectBox);
                if (cropping >= 0.10 && cropping <= 0.30)
                {
                    PlacedOccludingObjects[index] = placedObject;
                    return;
                }
            }
        }
Example #26
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        // Unity.Mathematics.Random
        // Seed cannot be 0 (zero).
        var random     = new Random((uint)Environment.TickCount);
        var entityList = new NativeList <Entity>(Allocator.TempJob);

        Entities
        .WithStoreEntityQueryInField(ref m_Query)
        .ForEach((Instantiator instantiator) => {
            // This will set the Length and resize the internal array if needed
            entityList.ResizeUninitialized(instantiator.Count);

            EntityManager.Instantiate(instantiator.Prefab, entityList);

            for (var entityIndex = 0; entityIndex < entityList.Length; entityIndex++)
            {
                var entity   = entityList[entityIndex];
                var position = new float3()
                {
                    x = UnityEngine.Random.Range(-2.5f, 2.5f), y = UnityEngine.Random.Range(2f, 20f), z = UnityEngine.Random.Range(-2.5f, 2.5f)
                };
                EntityManager.SetComponentData(entity, new Translation
                {
                    Value = random.NextFloat3Direction() * random.NextFloat(-2, 2)
                });

                EntityManager.SetComponentData(entity, new Rotation
                {
                    Value = random.NextQuaternionRotation()
                });
            }
        })
        .WithStructuralChanges()
        .WithoutBurst()
        .Run();

        entityList.Dispose();

        // That's a batch operation for all entities captures in the query and scale really well.
        EntityManager.DestroyEntity(m_Query);

        return(inputDeps);
    }
Example #27
0
        public void MeshCollider_Create_WhenTriangleIndexOutOfRange_Throws()
        {
            int numTriangles = 10;
            var vertices     = new NativeArray <float3>(numTriangles * 3, Allocator.Persistent);
            var triangles    = new NativeArray <int3>(numTriangles, Allocator.Persistent);

            try
            {
                for (int i = 0; i < numTriangles; i++)
                {
                    int firstVertexIndex = i * 3;

                    vertices[firstVertexIndex]     = new float3(firstVertexIndex, 1f * (firstVertexIndex % 2), firstVertexIndex + 1);
                    vertices[firstVertexIndex + 1] = new float3(firstVertexIndex + 1, 1f * ((firstVertexIndex + 1) % 2), firstVertexIndex + 2);
                    vertices[firstVertexIndex + 2] = new float3(firstVertexIndex + 2, 1f * ((firstVertexIndex + 2) % 2), firstVertexIndex + 3);
                    triangles[i] = new int3(firstVertexIndex, firstVertexIndex + 1, firstVertexIndex + 2);
                }

                Random rnd = new Random(0x12345678);

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

                    int triangleIndex    = indexToChange / 3;
                    int vertexInTriangle = indexToChange % 3;
                    int invalidValue     = rnd.NextInt() * (rnd.NextBool() ? -1 : 1);

                    var triangle = triangles[triangleIndex];
                    triangle[vertexInTriangle] = invalidValue;
                    triangles[triangleIndex]   = triangle;

                    Assert.Throws <ArgumentException>(() => MeshCollider.Create(vertices, triangles));

                    triangle[vertexInTriangle] = indexToChange;
                    triangles[triangleIndex]   = triangle;
                }
            }
            finally
            {
                triangles.Dispose();
                vertices.Dispose();
            }
        }
Example #28
0
    // Start is called before the first frame update
    void Start()
    {
        spawnedCount = initialZombieSpawnCount;
        Unity.Mathematics.Random rand = new Unity.Mathematics.Random(42);
        var  prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(zombiePrefab, World.Active);
        var  entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        uint count         = 0;

        while (count++ < initialZombieSpawnCount)
        {
            var instance = entityManager.Instantiate(prefab);
            var space    = rand.NextInt2(minPos, maxPos);
            space.x += rand.NextInt(-2, 2);
            space.y += rand.NextInt(-2, 2);

            while (usedPositions.Contains(space))
            {
                space = rand.NextInt2(minPos, maxPos);
            }

            usedPositions.Add(space);

            var position = transform.TransformPoint(new float3(space.x, 1, space.y));
            entityManager.SetComponentData(instance, new Translation {
                Value = position
            });

            var movementData = entityManager.GetComponentData <MovementComponent>(instance);
            // todo: the ones that can maneuver should be faster
            // todo: leaders -> force outer zombies to stick around them
            movementData.speed += rand.NextFloat(-6f, 1f);
            entityManager.SetComponentData(instance, movementData);
        }

        EntityArchetype arch = entityManager.CreateArchetype(typeof(ZombieSpawnerComponent));
        Entity          e    = entityManager.CreateEntity(arch);

        entityManager.SetComponentData(e, new ZombieSpawnerComponent {
            prefab = prefab
        });
        entityManager.Instantiate(e);

        // StartCoroutine(SpawnZombieBatch());
    }
Example #29
0
    // Create children that fill a single orbit, equally spaced
    // https://en.wikipedia.org/wiki/Klemperer_rosette
    public void ExpandRosette(ref Random random, int vertices)
    {
        //Debug.Log("Expanding Rosette");

        // Rosette children replace the parent, parent orbital node is left empty
        Empty = true;

        // Masses in a rosette alternate, so every sequential pair has the same shared mass
        var sharedMass = Mass / vertices * 2;

        // Proportion of the masses of sequential pairs is random, but only for even vertex counts
        var proportion = vertices % 2 == 0 ? random.NextFloat(.5f, .95f) : .5f;

        // Place children at a fixed distance in the center of the range
        var dist = (ChildDistanceMinimum + ChildDistanceMaximum) / 2;

        // Position of first child
        var p0 = new float2(0, dist);

        // Position of second child
        var p1 = OrbitData.Evaluate(1.0f / vertices) * dist;

        // Maximum child distance is half the distance to the neighbor minus the neighbor's radius
        var p0ChildDist = (distance(p0, p1) * proportion - Settings.PlanetSafetyRadius.Evaluate(sharedMass * (1 - proportion))) * .75f;
        var p1ChildDist = (distance(p0, p1) * (1 - proportion) - Settings.PlanetSafetyRadius.Evaluate(sharedMass * proportion)) * .75f;

        for (int i = 0; i < vertices; i++)
        {
            var child = new GeneratorPlanet
            {
                Settings             = Settings,
                Parent               = this,
                Mass                 = sharedMass * (i % 2 == 0 ? proportion : 1 - proportion), // Masses alternate
                Distance             = dist,
                Phase                = (float)i / vertices,
                ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
            };
            child.ChildDistanceMinimum = Settings.PlanetSafetyRadius.Evaluate(child.Mass) * 2;
            //child.Period = Settings..Evaluate(child.Distance);
            Children.Add(child);
        }

        ChildDistanceMinimum = dist + p0ChildDist;
    }
Example #30
0
        public unsafe void ConvexConvexDistanceEdgeCaseTest()
        {
            Random rnd      = new Random(0x90456148);
            uint   dbgShape = 0;
            uint   dbgTest  = 0;

            int numShapes = 500;
            int numTests  = 50;

            if (dbgShape > 0)
            {
                numShapes = 1;
                numTests  = 1;
            }

            for (int iShape = 0; iShape < numShapes; iShape++)
            {
                if (dbgShape > 0)
                {
                    rnd.state = dbgShape;
                }
                uint shapeState = rnd.state;

                // Generate a random collider
                ConvexCollider *collider = (ConvexCollider *)TestUtils.GenerateRandomConvex(ref rnd).GetUnsafePtr();

                for (int iTest = 0; iTest < numTests; iTest++)
                {
                    if (dbgTest > 0)
                    {
                        rnd.state = dbgTest;
                    }
                    uint testState = rnd.state;

                    // Generate random transform
                    float      distance        = math.pow(10.0f, rnd.NextFloat(-15.0f, -1.0f));
                    float      angle           = math.pow(10.0f, rnd.NextFloat(-15.0f, 0.0f));
                    MTransform queryFromTarget = new MTransform(
                        (rnd.NextInt(10) > 0) ? quaternion.AxisAngle(rnd.NextFloat3Direction(), angle) : quaternion.identity,
                        (rnd.NextInt(10) > 0) ? rnd.NextFloat3Direction() * distance : float3.zero);
                    TestConvexConvexDistance(collider, collider, queryFromTarget, "ConvexConvexDistanceEdgeCaseTest failed " + iShape + ", " + iTest + " (" + shapeState + ", " + testState + ")");
                }
            }
        }