Exemplo n.º 1
0
    public unsafe int GetPoints(int i, float3 *dest)
    {
        Unity.Mathematics.Random rng = new Unity.Mathematics.Random(m_Seeds[i]);
        GetResolution(ref rng, out int res0, out int res1);
        float scale  = rng.NextBool() ? 1.0f : rng.NextFloat(1.0f, 5.0f);
        float radius = rng.NextFloat(0.01f, 1.0f / scale);

        // Generate points
        int numPoints;

        if (res1 == 0)
        {
            // Random scattered points
            for (int iPoint = 0; iPoint < res0; iPoint++)
            {
                dest[iPoint] = math.normalize(rng.NextFloat3(-1, 1)) * radius;
            }
            numPoints = res0;
        }
        else
        {
            // Spherical coordinates
            int iPoint = 0;
            for (int iPhi = 0; iPhi < res0; iPhi++)
            {
                float phi    = (2 * iPhi + 1) * math.PI / res0;
                float sinPhi = math.sin(phi);
                float cosPhi = math.cos(phi);
                for (int iTheta = 0; iTheta < res1; iTheta++)
                {
                    float theta    = 0.5f * (2 * iTheta + 1) * math.PI / res1;
                    float sinTheta = math.sin(theta);
                    float cosTheta = math.cos(theta);
                    dest[iPoint++] = new float3(radius * sinTheta * cosPhi, radius * sinTheta * sinPhi, radius * cosTheta);
                }
            }
            numPoints = iPoint;
        }

        // Offset, scale and rotate
        float3     center      = rng.NextBool() ? float3.zero : rng.NextFloat3(1.0f);
        quaternion orientation = rng.NextBool() ? quaternion.identity : rng.NextQuaternionRotation();

        for (int iPoint = 0; iPoint < numPoints; iPoint++)
        {
            dest[iPoint] = math.mul(orientation, dest[iPoint] * new float3(scale, 1, 1) + center);
        }

        return(numPoints);
    }
        public void ControllerManater_update()
        {
            var random = new Random();

            random.InitState(1234567);

            using (var buffer = new NativeList <ControllerUnit>(ControllerBuffer.MaxFrames, Allocator.Persistent))
            {
                const int NUM        = 10;
                double    time       = 0;
                var       file_path0 = Application.dataPath + "/../tmp.txt";
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(file_path0))
                {
                    var device = new ControllerDevice(buffer);
                    for (var i = 0; i < NUM; ++i)
                    {
                        var ppos = random.NextFloat3();
                        var tpos = random.NextFloat3();
                        device.Update(time, ppos, tpos, true /* testing */);
                        time += 1.0 / 60.0;

                        var unit = device.GetCurrent();
                        sw.WriteLine(unit.ToString());
                    }
                    Assert.AreEqual(NUM, buffer.Length);

                    sw.WriteLine("----");

                    for (var i = 0; i < buffer.Length; ++i)
                    {
                        var unit = buffer[i];
                        sw.WriteLine(unit.ToString());
                    }

                    sw.WriteLine("----");

                    var replay = new ControllerReplay();
                    for (var i = 0; i < NUM * 10; ++i)
                    {
                        var ppos = random.NextFloat3();
                        var tpos = random.NextFloat3();
                        var unit = replay.Step(buffer, ppos, tpos);
                        time += 1.0 / 60.0;
                        sw.WriteLine(unit.ToString());
                    }
                }
            }
        }
Exemplo n.º 3
0
    void SpawnMeteor()
    {
        var elapsedFromLastSpawnedAt = Time.time - lastSpawnedAt;

        if (elapsedFromLastSpawnedAt < _spawnInterval)
        {
            return;
        }

        var transform        = this.transform;
        var meteorGameObject = Instantiate(meteorPrefab, transform);

        var meteor = meteorGameObject.GetComponent <Meteor>();

        meteor.speed         = _meteorSpeed;
        meteor.rotationAxis  = normalize(random.NextFloat3());
        meteor.rotationSpeed = meteorRotationSpeedRange.x + (meteorRotationSpeedRange.x - meteorRotationSpeedRange.y) * random.NextFloat();

        var meteorPosition = meteorGameObject.transform.position;
        var lanePosition   = (Lane.Position)(Mathf.Abs(random.NextInt()) % 3);

        meteorPosition.x = lane.GetTargetXFromPosition(lanePosition);
        meteorGameObject.transform.position = meteorPosition;

        _spawnInterval -= _spawnInterval * spawnIntervalReductionRate * elapsedFromLastSpawnedAt;
        _meteorSpeed   += _meteorSpeed * meteorSpeedIncreaseRate * elapsedFromLastSpawnedAt;

        var microStarParticleMain = microStarParticle.main;

        microStarParticleMain.startSpeedMultiplier = _meteorSpeed;

        lastSpawnedAt = Time.time;
    }
Exemplo n.º 4
0
        public void Execute(ref RandomMotion motion, [ReadOnly] ref Translation position, ref PhysicsVelocity velocity, [ReadOnly] ref PhysicsMass mass)
        {
            motion.CurrentTime += deltaTime;

            random.InitState((uint)(motion.CurrentTime * 1000));
            var currentOffset = position.Value - motion.InitialPosition;
            var desiredOffset = motion.DesiredPosition - motion.InitialPosition;

            // If we are close enough to the destination pick a new destination
            if (math.lengthsq(position.Value - motion.DesiredPosition) < motion.Tolerance)
            {
                var min = new float3(-math.abs(motion.Range));
                var max = new float3(math.abs(motion.Range));
                desiredOffset          = random.NextFloat3(min, max);
                motion.DesiredPosition = desiredOffset + motion.InitialPosition;
            }
            var offset = desiredOffset - currentOffset;

            // Smoothly change the linear velocity
            velocity.Linear = math.lerp(velocity.Linear, offset, motion.Speed);
            if (mass.InverseMass != 0)
            {
                velocity.Linear -= gravity * deltaTime;
            }
        }
Exemplo n.º 5
0
    protected override void OnUpdate()
    {
        var   random        = new Random();
        float deltaTime     = Time.DeltaTime;
        var   stepComponent = HasSingleton <PhysicsStep>() ? GetSingleton <PhysicsStep>() : PhysicsStep.Default;

        Entities
        .WithName("ApplyRandomMotion")
        .WithBurst()
        .ForEach((ref RandomMotion motion, ref PhysicsVelocity velocity, in Translation position, in PhysicsMass mass) =>
        {
            motion.CurrentTime += deltaTime;

            random.InitState((uint)(motion.CurrentTime * 1000));
            var currentOffset = position.Value - motion.InitialPosition;
            var desiredOffset = motion.DesiredPosition - motion.InitialPosition;
            // If we are close enough to the destination pick a new destination
            if (math.lengthsq(position.Value - motion.DesiredPosition) < motion.Tolerance)
            {
                var min                = new float3(-math.abs(motion.Range));
                var max                = new float3(math.abs(motion.Range));
                desiredOffset          = random.NextFloat3(min, max);
                motion.DesiredPosition = desiredOffset + motion.InitialPosition;
            }
            var offset = desiredOffset - currentOffset;
            // Smoothly change the linear velocity
            velocity.Linear = math.lerp(velocity.Linear, offset, motion.Speed);
            if (mass.InverseMass != 0)
            {
                velocity.Linear -= stepComponent.Gravity * deltaTime;
            }
        }).Schedule();
Exemplo n.º 6
0
    void Start()
    {
        var settings      = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
        var prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        var random        = new Unity.Mathematics.Random(853);

        for (int i = 0; i < boidCount; ++i)
        {
            var instance = entityManager.Instantiate(prefab);
            var position = transform.TransformPoint(random.NextFloat3(1f));

            entityManager.SetComponentData(instance, new Translation {
                Value = position
            });
            entityManager.SetComponentData(instance, new Rotation {
                Value = quaternion.identity
            });
            entityManager.SetComponentData(instance, new NonUniformScale {
                Value = new float3(boidScale.x, boidScale.y, boidScale.z)
            });
            entityManager.SetComponentData(instance, new Velocity {
                Value = random.NextFloat3Direction() * param.initSpeed
            });
            entityManager.SetComponentData(instance, new Acceleration {
                Value = float3.zero
            });

            // Dynamic Buffer の追加
            entityManager.AddBuffer <NeighborsEntityBuffer>(instance);
        }
    }
Exemplo n.º 7
0
    // Start is called before the first frame update
    void Start()
    {
        store         = new BlobAssetStore();
        entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        var    settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, store);
        Entity boid     = GameObjectConversionUtility.ConvertGameObjectHierarchy(boidPrefab, settings);

        Unity.Mathematics.Random rand = new Unity.Mathematics.Random((uint)System.DateTime.Now.Millisecond);

        for (int i = 0; i < boidSize; ++i)
        {
            var        instance = entityManager.Instantiate(boid);
            float3     xyz      = rand.NextFloat3(minBound, maxBound);
            quaternion q        = rand.NextQuaternionRotation();
            entityManager.SetComponentData(instance, new Translation {
                Value = xyz
            });
            entityManager.SetComponentData(instance, new Rotation {
                Value = q
            });

            float3 velocity = math.mul(q, new float3(0, 0, rand.NextFloat(1f, 10f)));
            entityManager.SetComponentData(instance, new SteerVelocity {
                velocity = velocity, lastVelocity = velocity
            });

            if (entityManager.HasComponent <SteerWander>(instance))
            {
                entityManager.AddComponentData(instance, new SteerWanderEdit()
                {
                    qrot = quaternion.identity
                });
            }
        }
    }
Exemplo n.º 8
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;
                }
            }
        }
Exemplo n.º 9
0
        public void 正しく圧縮できているかチェック()
        {
            const int N = 100;
            //const float EPS = 0.01f;
            const float EPS = 1.0f;

            var quarArr   = new Quaternion[N];
            var quat32Arr = new Quaternion32[N];

            var forward = new float3(0.0f, 0.0f, 1.0f);
            var rnd     = new Random((uint)System.DateTime.Now.Ticks);

            for (int i = 0; i < N; ++i)
            {
                var axis  = rnd.NextFloat3();
                var angle = rnd.NextFloat() * math.PI;

                var orig = quarArr[i] = quaternion.AxisAngle(axis, angle);
                quat32Arr[i] = Quaternion32.Compressed(orig);
                var result = quat32Arr[i].Decompressed();
                var ffa    = math.rotate(orig, forward);
                var ffb    = math.rotate(result, forward);
                Debug.Log($"ffa:{ffa}\nffb:{ffb}");
                Assert.IsTrue(NearEqual(ffa, ffb, EPS), $"ffa:{ffa}\nffb:{ffb}");
            }
        }
Exemplo n.º 10
0
        private void GenerateEntities()
        {
            var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

            // using (var spriteEntities = new NativeArray<Entity>(entitiesToSpawn, Allocator.Temp))
            var spriteEntities = new NativeArray <Entity>(entitiesToSpawn, Allocator.Temp);
            // {
            var spriteArchetype = entityManager.CreateArchetype(
                typeof(RenderMesh),
                typeof(RenderBounds),
                typeof(LocalToWorld),
                typeof(Translation));

            entityManager.CreateEntity(spriteArchetype, spriteEntities);

            var rnd = new Unity.Mathematics.Random((uint)System.DateTime.UtcNow.Ticks);

            for (var i = 0; i < entitiesToSpawn; ++i)
            {
                var spriteEntity = spriteEntities[i];

                entityManager.SetSharedComponentData(spriteEntity, new RenderMesh
                {
                    mesh     = spriteMesh,
                    material = spriteMaterial
                });

                entityManager.SetComponentData(spriteEntity, new Translation
                {
                    Value = rnd.NextFloat3(new float3(-5, -3, 0), new float3(5, 3, 0))
                });
            }
            // }
            spriteEntities.Dispose();
        }
Exemplo n.º 11
0
        void Start()
        {
            var manager   = World.Active.GetOrCreateManager <EntityManager>();
            var archetype = manager.CreateArchetype(
                typeof(Position),
                typeof(Rotation),
                typeof(Scale),
                typeof(Velocity),
                typeof(Acceleration),
                typeof(NeighborsEntityBuffer),
                typeof(MeshInstanceRenderer));
            var random = new Unity.Mathematics.Random(853);

            for (int i = 0; i < boidCount; ++i)
            {
                var entity = manager.CreateEntity(archetype);
                manager.SetComponentData(entity, new Position {
                    Value = random.NextFloat3(1f)
                });
                manager.SetComponentData(entity, new Rotation {
                    Value = quaternion.identity
                });
                manager.SetComponentData(entity, new Scale {
                    Value = new float3(boidScale.x, boidScale.y, boidScale.z)
                });
                manager.SetComponentData(entity, new Velocity {
                    Value = random.NextFloat3Direction() * param.initSpeed
                });
                manager.SetComponentData(entity, new Acceleration {
                    Value = float3.zero
                });
                manager.SetSharedComponentData(entity, renderer);
            }
        }
        public void RandomNotZero()
        {
            Unity.Mathematics.Random random = Random();
            bool notZero = random.NextInt() != 0 && !random.NextFloat3().Equals(float3.zero);

            Assert.IsTrue(notZero);
        }
Exemplo n.º 13
0
        public void GetNextRandomPosition(out float3 pos, out quaternion rot, out float3 forward, out float2 localPos, out float speed, out int2 gridId)
        {
            int find = 0;

            pos      = new float3();
            rot      = new quaternion();
            forward  = new float3();
            gridId   = new int2();
            speed    = 0;
            localPos = new float2();
            float3 min = startPos - Size / 2;
            float3 max = startPos + Size / 2;

            while (find == 0)
            {
                pos    = RandomGen.NextFloat3(min, max);
                gridId = GetGridId(pos);
                if (!IsWalkable(gridId))
                {
                    continue;
                }
                pos.y     = 0;
                forward   = RandomGen.NextFloat3Direction();
                forward.y = 0;
                forward   = math.normalize(forward);
                rot       = quaternion.LookRotation(forward, new float3(0, 1, 0));
                localPos  = GetLocalPos(gridId, pos);
                speed     = RandomGen.NextFloat(1.0f, 2.0f);
                find      = 1;
            }

            return;
        }
Exemplo n.º 14
0
        protected override void SingletonAwake()
        {
            SystemsPaused = true;

            RenderMesh = new RenderMesh
            {
                mesh     = Mesh,
                material = Material
            };
            Bounds = Mesh.bounds.ToAABB();

            var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

            const int NumberOfBodies = 100000;
            var       random         = new Unity.Mathematics.Random(UInt32.MaxValue);
            var       entities       = entityManager.CreateEntity(Archetypes.BaseBodyArchetype, NumberOfBodies, Allocator.Temp);

            for (int i = 0; i < entities.Length; ++i)
            {
                var entity   = entities[i];
                var position = (double3)math.normalize((random.NextFloat3() * 2f) - 1f) * 100f;
                CreateBody(entityManager, entity, position, 0.25f);
            }
            entities.Dispose();

            //TestBed();
        }
Exemplo n.º 15
0
        public unsafe void ConvexConvexDistanceTest()
        {
            Random rnd     = new Random(0x12345678);
            uint   dbgTest = 0;

            int numTests = 5000;

            if (dbgTest > 0)
            {
                numTests = 1;
            }

            for (int i = 0; i < numTests; i++)
            {
                // Save state to repro this query without doing everything that came before it
                if (dbgTest > 0)
                {
                    rnd.state = dbgTest;
                }
                uint state = rnd.state;

                // Generate random query inputs
                ConvexCollider *target          = (ConvexCollider *)TestUtils.GenerateRandomConvex(ref rnd).GetUnsafePtr();
                ConvexCollider *query           = (ConvexCollider *)TestUtils.GenerateRandomConvex(ref rnd).GetUnsafePtr();
                MTransform      queryFromTarget = new MTransform(
                    (rnd.NextInt(10) > 0) ? rnd.NextQuaternionRotation() : quaternion.identity,
                    rnd.NextFloat3(-3.0f, 3.0f));
                TestConvexConvexDistance(target, query, queryFromTarget, "ConvexConvexDistanceTest failed " + i + " (" + state.ToString() + ")");
            }
        }
Exemplo n.º 16
0
 public void Execute(int index)
 {
     Random.InitState((uint)(Random.state + index));
     Translations[index] = new Translation()
     {
         Value = Random.NextFloat3(Min, Max)
     };
     Points[index] = new Point(Random.NextInt(PointMin, PointMax));
 }
    private void CreateEntities()
    {
        var rnd = new Random(12345);

        counter++;
        for (int i = 0; i < 2000; i++)
        {
            CreateEntity(rnd.NextFloat3(-value * counter, value * counter), renderMeshFrames[rnd.NextInt(0, renderMeshFrames.Count - 1)]);
        }
    }
Exemplo n.º 18
0
 void Update()
 {
     for (var i = 0; i < 4; ++i)
     {
         var pos = random_.NextFloat3(-100, 100);
         var dir = random_.NextFloat3Direction();
         var rot = quaternion.LookRotation(dir, new float3(0, 1, 0));
         MissileSystem.Instantiate(MissileManager.Prefab, pos, rot);
     }
 }
Exemplo n.º 19
0
            public void Execute()
            {
                var points = new NativeArray <float3>(1024, Allocator.Temp);
                var random = new Random(1234);

                for (var i = 0; i < points.Length; ++i)
                {
                    points[i] = random.NextFloat3(new float3(-1f), new float3(1f));
                }
                ConvexCollider.Create(points, ConvexHullGenerationParameters.Default).Release();
            }
Exemplo n.º 20
0
    void Explode()
    {
        isRunning = false;

        var rigidbody = GetComponent <Rigidbody>();

        rigidbody.isKinematic = false;
        rigidbody.AddExplosionForce(explosionForce, random.NextFloat3(), explosionRadius);

        explodeCompletionSource.TrySetResult();
    }
Exemplo n.º 21
0
        void LeoECS()
        {
            _world = new EcsWorld();
            JobMoveSystem.MinSpeed         = param.minSpeed;
            JobMoveSystem.MaxSpeed         = param.maxSpeed;
            JobMoveSystem.BoidScale        = boidScale;
            JobMoveSystem.WallScale        = param.wallScale * 0.5f;
            JobMoveSystem.WallDistance     = param.wallDistance;
            JobMoveSystem.WallWeight       = param.wallWeight;
            JobMoveSystem.NeighborFov      = math.cos(math.radians(param.neighborFov));
            JobMoveSystem.NeighborDistance = param.neighborDistance;
            JobMoveSystem.SeparationWeight = param.separationWeight;
            JobMoveSystem.AlignmentWeight  = param.alignmentWeight;
            JobMoveSystem.CohesionWeight   = param.cohesionWeight;
            JobMoveSystem.EntitiesCount    = boidCount;
            JobMoveSystem.NumBoidsPerJob   = boidCount / System.Environment.ProcessorCount;

            if (BoidsVisualisationSystem._nativeMatrices.IsCreated)
            {
                BoidsVisualisationSystem._nativeMatrices.Dispose();
            }
            BoidsVisualisationSystem._nativeMatrices = new NativeArray <Matrix4x4> (boidCount, Allocator.Persistent);
            BoidsVisualisationSystem._matrices       = new Matrix4x4[boidCount];

            var timeSystem = new TimeSystem();

            _systems = new EcsSystems(_world);
            _systems
            .Add(timeSystem)
            .Add(new BoidsSimulationSystem())
            .Add(new JobMoveSystem())
            .Add(new BoidsVisualisationSystem()
            {
                mesh = mesh, material = material, scale = boidScale
            })
            .Inject(timeSystem)
            .Initialize();
            var random = new Unity.Mathematics.Random(853);

            BoidEntityData.Create(boidCount);

            for (int i = 0; i < boidCount; ++i)
            {
                var initSpeed = param.initSpeed;
                //init them with these default values
                var boid = _world.CreateEntityWith <BoidEntityData> ();
                boid.id           = i;
                boid.Position     = random.NextFloat3(1f);
                boid.Velocity     = random.NextFloat3Direction() * initSpeed;;
                boid.Acceleration = float3.zero;
            }
            _world.ProcessDelayedUpdates();
        }
    protected static void RandomPointsOnCircle(float3 center, float3 range, ref NativeArray <float3> positions, ref NativeArray <quaternion> rotations, int seed = 0)
    {
        var count = positions.Length;
        // initialize the seed of the random number generator
        var random = new Unity.Mathematics.Random((uint)seed);

        for (int i = 0; i < count; i++)
        {
            positions[i] = center + random.NextFloat3(-range, range);
            rotations[i] = random.NextQuaternionRotation();
        }
    }
Exemplo n.º 23
0
    public static void SpawnParticles()
    {
        var entityManager = World.Active.GetOrCreateManager <EntityManager>();
        var random        = new Unity.Mathematics.Random(835483957);

        for (int i = 0; i < 1000; i++)
        {
            Entity particle = entityManager.CreateEntity(WaterParticleArchetype);
            entityManager.AddSharedComponentData(particle, WaterParticleLook);
            var position = random.NextFloat3() * Constants.MAX_WORLD_SIZE - Constants.HIGH_WORLD_EDGE;
            position.y = 0;
            var velocity = random.NextFloat3() * 4f - 2;
            velocity.y = 0;

            float lifeTime = random.NextFloat() * Constants.PARTICLE_LIFETIME;

            float scaleX = random.NextFloat() * .3f + 0.3f;
            float scaleZ = random.NextFloat() * 1.5f + 0.8f;

            var angle = random.NextFloat() * 180;

            var q = quaternion.RotateY(angle);

            entityManager.SetComponentData(particle, new Scale {
                Value = new float3(scaleX, 0.1f, scaleZ)
            });
            entityManager.SetComponentData(particle, new Position {
                Value = position
            });
            entityManager.SetComponentData(particle, new Rotation {
                Value = q
            });
            entityManager.SetComponentData(particle, new VelocityComponent {
                Value = new float3(1, 0, 0)
            });
            entityManager.SetComponentData(particle, new ParticleComponent {
                LifeTimeLeft = lifeTime
            });
        }
    }
Exemplo n.º 24
0
    void Start()
    {
        var rand   = new Unity.Mathematics.Random(_randomSeed);
        var parent = transform;
        var rot    = quaternion.identity;

        for (var i = 0; i < _instanceCount; i++)
        {
            var pos = (rand.NextFloat3() - 0.5f) * _extent;
            pos = parent.TransformPoint(pos);
            Instantiate(_prefab, pos, rot, parent);
        }
    }
        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            var target = playerData as Transform;

            if (target == null)
            {
                return;
            }

            var t    = (float)playable.GetTime();
            var id   = (uint)(t * 1e+6f % 0xfffffff);
            var rand = new Unity.Mathematics.Random((randomSeed + 1) ^ id);

            var p = rand.NextFloat3();
            var r = rand.NextFloat3();

            p = (p * 2 - 1) * positionAmount * info.weight;
            r = (r * 2 - 1) * rotationAmount * info.weight;

            target.localPosition += (Vector3)p;
            target.localRotation  = Quaternion.Euler(r) * target.localRotation;
        }
Exemplo n.º 26
0
    public void RandomPointsOnCircle(float3 center, float3 range, ref NativeArray <float3> positions, ref NativeArray <quaternion> rotations)
    {
        var count = positions.Length;

        // Initialize the seed of the random number generator


        for (int i = 0; i < count; i++)
        {
            positions[i] = center + random.NextFloat3(-range, range);
            rotations[i] = random.NextQuaternionRotation();
        }
    }
 protected override void OnCreate()
 {
     for (int i = 0; i < CacheSize; i++)
     {
         SubOneFloats.Add(rand.NextFloat());
         Directions.Add(rand.NextFloat3(MoveRandom.DirectionMin, MoveRandom.DirectionMax));
         Angles.Add(rand.NextFloat(0f, Mathf.PI * 2));
         LifeSpans.Add(rand.NextFloat(1f, 15f));
         CenterDists.Add(rand.NextFloat(radius));
         CubeTypes.Add(rand.NextUInt((uint)SpawnerSystem.SpawnOdds));
     }
     base.OnCreate();
 }
Exemplo n.º 28
0
    private void Initialize()
    {
        EntityManager entityManager = World.Active.EntityManager;

        NativeArray <Entity> cubeEntities = new NativeArray <Entity>(numberOfEntitiesToSpawn, Allocator.Temp);

        EntityArchetype cubeArchetype = entityManager.CreateArchetype(
            typeof(RenderMesh),
            typeof(LocalToWorld),
            typeof(Translation),
            typeof(Rotation),
            typeof(NonUniformScale),
            typeof(Rotator)
            );

        entityManager.CreateEntity(cubeArchetype, cubeEntities);

        Unity.Mathematics.Random rnd = new Unity.Mathematics.Random();
        rnd.InitState((uint)System.DateTime.UtcNow.Ticks);

        for (int i = 0; i < cubeEntities.Length; i++)
        {
            Entity cubeEntity = cubeEntities[i];
            entityManager.SetSharedComponentData(cubeEntity, new RenderMesh {
                mesh = config.Mesh, material = config.Material
            });
            entityManager.SetComponentData(cubeEntity, new Translation {
                Value = rnd.NextFloat3(new float3(config.MinEntityPosition.x, 0, config.MinEntityPosition.y), new float3(config.MaxEntityPosition.x, 0, config.MaxEntityPosition.y))
            });
            entityManager.SetComponentData(cubeEntity, new NonUniformScale {
                Value = rnd.NextFloat3(new float3(config.MinEntityScale.x, config.MinEntityScale.y, config.MinEntityScale.x), new float3(config.MaxEntityScale.x, config.MaxEntityScale.y, config.MaxEntityScale.x))
            });
            entityManager.SetComponentData(cubeEntity, new Rotator {
                Rotation = rnd.NextFloat(0, 360), RotationSpeed = rnd.NextFloat(config.MinSpin, config.MaxSpin)
            });
        }

        cubeEntities.Dispose();
    }
        void SpawnSphere()
        {
            BlobAssetReference <Collider> sourceCollider = entityManager.GetComponentData <PhysicsCollider>(sourceEntity).Value;

            Unity.Mathematics.Random random = new Unity.Mathematics.Random();
            random.InitState(10);
            for (int i = 0; i < spawnCount; i++)
            {
                var instance = entityManager.Instantiate(sourceEntity);
                entityManager.SetComponentData(instance, new Translation {
                    Value = center + random.NextFloat3(-range, range)
                });
            }
        }
Exemplo n.º 30
0
    protected override void OnUpdate()
    {
        if (!init)
        {
            var random          = new Unity.Mathematics.Random(853);
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = whalesGhostSerializerCollection.FindGhostType <BoidSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;

            for (int i = 0; i < Bootstrap.Instance.boidCount; ++i)
            {
                var boid = EntityManager.Instantiate(prefab);

                EntityManager.SetComponentData(boid, new Translation {
                    Value = random.NextFloat3(1f)
                });
                EntityManager.SetComponentData(boid, new Rotation {
                    Value = quaternion.identity
                });
                EntityManager.SetComponentData(boid, new Velocity {
                    Value = random.NextFloat3Direction() * Bootstrap.Param.initSpeed
                });
                EntityManager.SetComponentData(boid, new Acceleration {
                    Value = float3.zero
                });
                EntityManager.AddBuffer <NeighborsEntityBuffer>(boid);
            }
            init = true;
        }

        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(string.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();

            var playerGhostId = whalesGhostSerializerCollection.FindGhostType <WhaleSnapshotData>();
            var playerPrefab  = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[playerGhostId].Value;
            var player        = EntityManager.Instantiate(playerPrefab);
            EntityManager.SetComponentData(player, new PlayerComponent {
                PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });
            PostUpdateCommands.AddBuffer <InputCommandData>(player);

            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });
            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }