Beispiel #1
0
            public void Execute(int i, TransformAccess transform)
            {
                Vector3 currentVelocity = ObjectVelocities[i];
                random  randomGen       = new random((uint)(i * Time + 1 + Seed));

                transform.position += transform.localToWorldMatrix.MultiplyVector(new Vector3(0, 0, 1)) * SwimSpeed * JobDeltaTime * randomGen.NextFloat(0.3f, 1.0f);

                if (currentVelocity != Vector3.zero)
                {
                    transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(currentVelocity), TurnSpeed * JobDeltaTime);
                }

                Vector3 currentPosition = transform.position;

                bool randomise = true;

                if (currentPosition.x > Center.x + Bounds.x / 2 || currentPosition.x < Center.x - Bounds.x / 2 || currentPosition.z > Center.z + Bounds.z / 2 || currentPosition.z < Center.z - Bounds.z / 2)
                {
                    Vector3 internalPosition = new Vector3(Center.x + randomGen.NextFloat(-Bounds.x / 2, Bounds.x / 2) / 1.3f, 0, Center.z + randomGen.NextFloat(-Bounds.z / 2, Bounds.z / 2) / 1.3f);
                    currentVelocity     = (internalPosition - currentPosition).normalized;
                    ObjectVelocities[i] = currentVelocity;
                    transform.rotation  = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(currentVelocity), TurnSpeed * JobDeltaTime * 2);
                    randomise           = false;
                }

                if (randomise)
                {
                    if (randomGen.NextInt(0, SwimChangeFrequency) <= 2)
                    {
                        ObjectVelocities[i] = new Vector3(randomGen.NextFloat(-1f, 1f), 0, randomGen.NextFloat(-1f, 1f));
                    }
                }
            }
 public void Execute(int index)
 {
     Directions[index] = new Vector3(
         Random.NextFloat(-SpreadFactor, SpreadFactor),
         Random.NextFloat(-SpreadFactor, SpreadFactor),
         Random.NextFloat(-SpreadFactor, SpreadFactor));
 }
        protected override PerformanceData CreateGraph(Entity entity, ref Rig rig, ProcessDefaultAnimationGraph graphSystem, ref PerformanceSetup setup)
        {
            if (!EntityManager.HasComponent <PerformanceSetupAsset>(entity))
            {
                throw new System.InvalidOperationException("Entity is missing a PerformanceSetupAsset IBufferElementData");
            }

            if (EntityManager.GetBuffer <PerformanceSetupAsset>(entity).Length != 2)
            {
                throw new System.InvalidOperationException("Entity needs 2 PerformanceSetupAssets");
            }

            var set  = graphSystem.Set;
            var data = new PerformanceData
            {
                Graph = graphSystem.CreateGraph()
            };
            var deltaTimeNode = graphSystem.CreateNode <ConvertDeltaTimeToFloatNode>(data.Graph);
            var timeNode      = graphSystem.CreateNode <TimeCounterNode>(data.Graph);
            var entityNode    = graphSystem.CreateNode(data.Graph, entity);

            var clipBuffer      = EntityManager.GetBuffer <PerformanceSetupAsset>(entity);
            var clipPlayerNodes = new NativeArray <NodeHandle <ClipPlayerNode> >(clipBuffer.Length, Allocator.Temp);

            // Clips to binary mixer
            data.InertialNode  = graphSystem.CreateNode <InertialBlendingNode>(data.Graph);
            clipPlayerNodes[0] = graphSystem.CreateNode <ClipPlayerNode>(data.Graph);
            clipPlayerNodes[1] = graphSystem.CreateNode <ClipPlayerNode>(data.Graph);

            set.SetData(clipPlayerNodes[0], ClipPlayerNode.KernelPorts.Speed, s_Random.NextFloat(0.1f, 1f));
            set.SetData(clipPlayerNodes[1], ClipPlayerNode.KernelPorts.Speed, s_Random.NextFloat(0.1f, 1f));
            set.SetData(timeNode, TimeCounterNode.KernelPorts.Speed, 1f);

            set.Connect(entityNode, deltaTimeNode, ConvertDeltaTimeToFloatNode.KernelPorts.Input);
            set.Connect(deltaTimeNode, ConvertDeltaTimeToFloatNode.KernelPorts.Output, clipPlayerNodes[0], ClipPlayerNode.KernelPorts.DeltaTime);
            set.Connect(deltaTimeNode, ConvertDeltaTimeToFloatNode.KernelPorts.Output, clipPlayerNodes[1], ClipPlayerNode.KernelPorts.DeltaTime);
            set.Connect(deltaTimeNode, ConvertDeltaTimeToFloatNode.KernelPorts.Output, timeNode, TimeCounterNode.KernelPorts.DeltaTime);
            set.Connect(clipPlayerNodes[0], ClipPlayerNode.KernelPorts.Output, data.InertialNode, InertialBlendingNode.KernelPorts.Input0);
            set.Connect(clipPlayerNodes[1], ClipPlayerNode.KernelPorts.Output, data.InertialNode, InertialBlendingNode.KernelPorts.Input1);
            set.Connect(timeNode, TimeCounterNode.KernelPorts.Time, data.InertialNode, InertialBlendingNode.KernelPorts.Time);
            set.Connect(timeNode, TimeCounterNode.KernelPorts.OutputDeltaTime, data.InertialNode, InertialBlendingNode.KernelPorts.DeltaTime);
            set.Connect(data.InertialNode, InertialBlendingNode.KernelPorts.Output, entityNode, NodeSet.ConnectionType.Feedback);

            set.SendMessage(clipPlayerNodes[0], ClipPlayerNode.SimulationPorts.Configuration, new ClipConfiguration {
                Mask = ClipConfigurationMask.LoopTime
            });
            set.SendMessage(clipPlayerNodes[1], ClipPlayerNode.SimulationPorts.Configuration, new ClipConfiguration {
                Mask = ClipConfigurationMask.LoopTime
            });
            set.SendMessage(clipPlayerNodes[0], ClipPlayerNode.SimulationPorts.Rig, rig);
            set.SendMessage(clipPlayerNodes[1], ClipPlayerNode.SimulationPorts.Rig, rig);
            set.SendMessage(clipPlayerNodes[0], ClipPlayerNode.SimulationPorts.Clip, clipBuffer[0].Clip);
            set.SendMessage(clipPlayerNodes[1], ClipPlayerNode.SimulationPorts.Clip, clipBuffer[1].Clip);
            set.SendMessage(data.InertialNode, InertialBlendingNode.SimulationPorts.Rig, rig);
            set.SendMessage(data.InertialNode, InertialBlendingNode.SimulationPorts.Duration, 1);

            return(data);
        }
        static Mesh CreateMesh(Material material)
        {
            var random = new Random();

            random.InitState(12345);

            var vertices = new Vector3[POINT_MAX * 2];

            for (var i = 0; i < POINT_MAX; ++i)
            {
                float x     = random.NextFloat(-RANGE, RANGE);
                float y     = random.NextFloat(-RANGE, RANGE);
                float z     = random.NextFloat(-RANGE, RANGE);
                var   point = new Vector3(x, y, z);
                vertices[i * 2 + 0] = point;
                vertices[i * 2 + 1] = point;
            }
            var indices = new int[POINT_MAX * 2];

            for (var i = 0; i < POINT_MAX * 2; ++i)
            {
                indices[i] = i;
            }
            var colors = new Color[POINT_MAX * 2];

            for (var i = 0; i < POINT_MAX; ++i)
            {
                colors[i * 2 + 0] = new Color(0f, 0f, 0f /* not used */, 1f);
                colors[i * 2 + 1] = new Color(0f, 0f, 0f /* not used */, 0f);
            }
            var uvs = new Vector2[POINT_MAX * 2];

            for (var i = 0; i < POINT_MAX; ++i)
            {
                uvs[i * 2 + 0] = new Vector2(1f, 0f);
                uvs[i * 2 + 1] = new Vector2(0f, 1f);
            }

            var mesh = new Mesh();

            mesh.name     = "debris";
            mesh.vertices = vertices;
            mesh.colors   = colors;
            mesh.uv       = uvs;
            mesh.bounds   = new Bounds(Vector3.zero, Vector3.one * 99999999);
            mesh.SetIndices(indices, MeshTopology.Lines, 0);
            mesh.UploadMeshData(true /* markNoLogerReadable */);

            _material = material;
            material.SetFloat("_Range", RANGE);
            material.SetFloat("_RangeR", 1f / RANGE);
            const float cpower = 0.4f;

            material.SetColor(MaterialColor, new Color(cpower, cpower, cpower));

            // mesh_ = mesh;
            return(mesh);
        }
Beispiel #5
0
        static string GetColorStringFromHash(uint hash)
        {
            var rnd = new Unity.Mathematics.Random();

            rnd.InitState(hash);

            var color    = Color.HSVToRGB(rnd.NextFloat(0.1f, 0.9f), rnd.NextFloat(0.5f, 1), rnd.NextFloat(0.5f, 1));
            var colorStr = ColorUtility.ToHtmlStringRGB(color);

            return(colorStr);
        }
        public void Convert(Entity entity, EntityManager manager, GameObjectConversionSystem converter)
        {
            InitRandom();
            float randomSpeed = s_random.NextFloat(1f, 5f);

            float   randomAngle     = s_random.NextFloat(0f, (float)(2.0 * System.Math.PI));
            Vector3 randomDirection = new Vector3(Mathf.Cos(randomAngle), 0f, Mathf.Sin(randomAngle));

            Ant a = new Ant {
                speed = randomSpeed, direction = randomDirection
            };

            manager.AddComponentData(entity, a);
        }
Beispiel #7
0
        public void Break()
        {
            if (PlacementSet.BreakAble)
            {
                if (_stuff != null)
                {
                    var explodable = _stuff.gameObject.AddComponent <Explodable>();
                    _stuff.gameObject.AddComponent <BoxCollider2D>();
                    explodable.allowRuntimeFragmentation = true;
                    explodable.fragmentLayer             = "Breaks";
                    explodable.extraPoints  = 10;
                    explodable.orderInLayer = 3;
                    explodable.explode();
                    Sounds.Get().PlayDestructionSound();
                    gameObject.GetComponent <BoxCollider2D>().enabled = false;

                    var fragments = explodable.fragments;
                    foreach (var f in fragments)
                    {
                        Destroy(f.GetComponent <PolygonCollider2D>(), _random.NextFloat(1.0f, 2.5f));
                        Destroy(f, 3f);
                    }

                    if (showAfterBreak.ShowObject != null)
                    {
                        showAfterBreak.ShowObject.gameObject.SetActive(true);
                    }
                    Destroy(gameObject, 2.0f);
                }
            }
        }
Beispiel #8
0
        public void Execute(ref ExecuteContext <Parameters, Providers> context)
        {
            if (context.Outputs.Count == 0)
            {
                return;
            }

            if (m_Random.state == 0)
            {
                m_Random.InitState(2747636419u);
            }

            var outputSampleBuffer = context.Outputs.GetSampleBuffer(0);
            var outputChannels     = outputSampleBuffer.Channels;
            var parameters         = context.Parameters;
            var inputCount         = context.Inputs.Count;

            for (var channel = 0; channel < outputChannels; ++channel)
            {
                var outputBuffer = outputSampleBuffer.GetBuffer(channel);
                for (var i = 0; i < inputCount; i++)
                {
                    var inputBuff = context.Inputs.GetSampleBuffer(i).GetBuffer(channel);
                    for (var s = 0; s < outputBuffer.Length; s++)
                    {
                        outputBuffer[s] += inputBuff[s];
                    }
                }

                for (var s = 0; s < outputBuffer.Length; s++)
                {
                    outputBuffer[s] += m_Random.NextFloat() * 2.0f - 1.0f + parameters.GetFloat(Parameters.Offset, s);
                }
            }
        }
            public void Execute(Entity entity, int index,
                                [ReadOnly, ChangedFilter] DynamicBuffer <PhysicsTriggerResults> physicsTriggerResults,
                                [ReadOnly] ref ActorAttribute3Offset <_HP> hpOffset,
                                [ReadOnly] ref ActorOwner actorOwner, [ReadOnly] ref Actor actor)
            {
                for (var i = 0; i < physicsTriggerResults.Length; ++i)
                {
                    var targetEntity = physicsTriggerResults[i].entity;

                    var hp = hpOffset.GetValue(random.NextFloat(0f, 1f));

                    if (hpModifyFromEntity.Exists(targetEntity))
                    {
                        hpModifyFromEntity[targetEntity].Add(new ActorAttribute3Modifys <_HP>
                        {
                            player = actorOwner.playerEntity,
                            type   = actor.actorType,
                            value  = hp,
                            attribute3ModifyType = Attribute3SubModifyType.ValueOffset
                        });
                    }

                    //
                    var translation = translationFromEntity[targetEntity];
                    AttributeModifyFxSpawner.createInServer(endCommandBuffer, index, actor.actorType, translation, hp, 0f, default);
                }
            }
Beispiel #10
0
        protected override void OnUpdate()
        {
            var random = new Unity.Mathematics.Random((uint)Random.Range(1, 100000));
            var buffer = PostAttackEntityBuffer.CreateCommandBuffer().AsParallelWriter();

            Dependency = Entities.ForEach(
                (Entity e, int entityInQueryIndex, in Attack attack, in Instigator attacker, in Target target, in BeamEffectStyle style, in HitLocation hitLoc, in SourceLocation sourceLoc) =>
            {
                var laserEffect = new BeamEffect()
                {
                    start    = sourceLoc.Position,
                    end      = hitLoc.Position,
                    lifetime = 0.2f
                };

                if (attack.Result == Attack.eResult.Miss)
                {
                    var delta       = new Unity.Mathematics.float3(random.NextFloat() - 0.5f, 0f, random.NextFloat() - 0.5f);
                    laserEffect.end = laserEffect.end + 6f * delta;
                }

                Entity effect = buffer.CreateEntity(entityInQueryIndex);
                buffer.AddComponent(entityInQueryIndex, effect, laserEffect);
                buffer.AddComponent(entityInQueryIndex, effect, style);
                buffer.AddComponent(entityInQueryIndex, effect, attacker);
                buffer.AddComponent(entityInQueryIndex, effect, target);
            }
Beispiel #11
0
        /// <summary>
        /// Generates one sample
        /// </summary>
        /// <returns>The generated sample</returns>
        public float Sample()
        {
            var rng = new Unity.Mathematics.Random(ScenarioBase.activeScenario.NextRandomState());

            return(SamplerUtility.TruncatedNormalSample(
                       rng.NextFloat(), range.minimum, range.maximum, mean, standardDeviation));
        }
Beispiel #12
0
        /// <summary>
        /// Generates one sample
        /// </summary>
        /// <returns>The generated sample</returns>
        public float Sample()
        {
            Initialize();
            var rng = new Unity.Mathematics.Random(ScenarioBase.activeScenario.NextRandomState());

            return(SamplerUtility.AnimationCurveSample(
                       m_IntegratedCurve, rng.NextFloat(), m_Interval, m_StartTime, m_EndTime));
        }
Beispiel #13
0
        protected override void OnUpdate()
        {
            // -- SpawnUnitsSystem_Main
            var rng = new Unity.Mathematics.Random((uint)(DateTime.Now.ToString().GetHashCode()));

            Entities
            .WithStructuralChanges()
            .WithoutBurst()
            .WithName("SpawnUnitsSystem_Main")
            .ForEach((Entity e, ref SpawnRequest spawnRequest) =>
            {
                var count    = spawnRequest.Count;
                var entities = EntityManager.CreateEntity(_archetype, (int)count, Allocator.Temp);

                foreach (var entity in entities)
                {
                    string name        = Names[rng.NextInt(0, Names.Length - 1)];
                    var nameCount      = ++_countByName[name];
                    _countByName[name] = nameCount;

                    EntityManager.SetName(entity, name + nameCount);
                    EntityManager.SetSharedComponentData(entity, new InPlace()
                    {
                        Place = Place.Home
                    });
                    EntityManager.SetComponentData(entity, new WorkStat()
                    {
                        Speed = rng.NextFloat(5f, 7f)
                    });
                    EntityManager.SetComponentData(entity, new EnergyStat()
                    {
                        Count = 100, FatiguePressure = rng.NextFloat(15f, 25f)
                    });
                    EntityManager.SetComponentData(entity, new EnergyRegeneration()
                    {
                        Value = rng.NextFloat(20f, 30f)
                    });
                }

                entities.Dispose();
                EntityManager.DestroyEntity(e);
            })
            .Run();
        }
Beispiel #14
0
        protected override void OnUpdate()
        {
            Entities
            .WithoutBurst()
            .WithStructuralChanges()
            .WithAll <EntitySpawnData>()
            .ForEach((Entity entity) => EntityManager.AddBuffer <EntityLifeTimeBuffer>(entity))
            .Run()
            ;

            var deltaTime = TimeSpan.FromSeconds(World.Time.DeltaTime);
            var random    = new Random((uint)Environment.TickCount);

            Entities
            .WithoutBurst()
            .WithStructuralChanges()
            .ForEach((Entity spawner, DynamicBuffer <EntityLifeTimeBuffer> entities, in EntitySpawnData data) =>
            {
                var ecb = new EntityCommandBuffer(Allocator.Temp);

                var newEntities = ecb.SetBuffer <EntityLifeTimeBuffer>(spawner);
                foreach (var entity in entities)
                {
                    var buffer       = entity;
                    buffer.LifeTime -= deltaTime;
                    if (buffer.LifeTime <= TimeSpan.Zero)
                    {
                        ecb.DestroyEntity(buffer.Entity);
                    }
                    else
                    {
                        newEntities.Add(buffer);
                    }
                }

                var count = data.Count - entities.Length;
                for (var i = 0; i < count; i++)
                {
                    var instance = ecb.Instantiate(data.Prefab);
                    var position = random.NextFloat3(data.PositionBounds.min, data.PositionBounds.max);
                    ecb.SetComponent(instance, new Translation {
                        Value = position
                    });
                    var lifetime = TimeSpan.FromSeconds(random.NextFloat(data.LifeTimeRange.x, data.LifeTimeRange.y));
                    newEntities.Add(new EntityLifeTimeBuffer {
                        Entity = instance, LifeTime = lifetime
                    });
                }

                ecb.Playback(EntityManager);
                ecb.Dispose();
            }).Run();
        }
Beispiel #15
0
            public void Execute(int index)
            {
                var rb = RigidBodies[index];

                var seed   = (uint)(index + 10000) * 100000;
                var random = new Unity.Mathematics.Random(seed);
                var t      = random.NextFloat();

                var point = Spline.JobSafe_GetPoint(Points, Mode, SplineSpace, localToWorldMatrix, ClosedSpline, t);


                var offset_x = random.NextFloat(RandomMinSpeed, RandomMaxSpeed) * 0.1f;
                var offset_z = random.NextFloat(RandomMinSpeed, RandomMaxSpeed) * 0.1f;

                rb.position = point.position + new Vector3(offset_x, 0f, offset_z);

                // speed
                var speed_x = random.NextFloat(RandomMinSpeed, RandomMaxSpeed);
                var speed_y = random.NextFloat(RandomMinSpeed, RandomMaxSpeed);
                var speed_z = random.NextFloat(RandomMinSpeed, RandomMaxSpeed);

                rb.velocity = new Vector3(speed_x, speed_y, speed_z);

                RigidBodies[index] = rb;
            }
Beispiel #16
0
        public static void Float()
        {
            Unity.Mathematics.Random rng = new Unity.Mathematics.Random(Helpers.GetRngSeed);

            Helpers.Test <float>(
                (array) =>
            {
                array.SIMD_MinMax(out float min, out float max);

                Assert.AreEqual(min, array.SIMD_Minimum());
                Assert.AreEqual(max, array.SIMD_Maximum());
            },
                () => rng.NextFloat(float.MinValue, float.MaxValue));
        }
Beispiel #17
0
            public void Execute(int index, TransformAccess transform)
            {
                Vector3 currentVelocity = fishVels[index];
                // 在Job中不允许用UnityEngine的Random.Range方法,只能使用MathRandom:
                // UnityException: Range can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene.
                URandom ranGen = new URandom((uint)(index * time + 1 + seed));

                transform.position += transform.localToWorldMatrix.MultiplyVector(Vector3.forward * swimSpeed * deltaTime * ranGen.NextFloat(0.3f, 1.0f));

                if (currentVelocity != Vector3.zero)
                {
                    transform.rotation = Quaternion.Lerp(
                        transform.rotation,
                        Quaternion.LookRotation(currentVelocity),
                        turnSpeed * deltaTime);
                }
                // 超出边界就朝中心游动
                if (transform.position.x > centerPos.x + spawnBounds.x / 2 ||
                    transform.position.x < centerPos.x - spawnBounds.x / 2 ||
                    transform.position.z > centerPos.z + spawnBounds.z / 2 ||
                    transform.position.z < centerPos.z - spawnBounds.z / 2)
                {
                    Vector3 internalPosition = new Vector3(centerPos.x + ranGen.NextFloat(-spawnBounds.x / 2, spawnBounds.x / 2), 0,
                                                           centerPos.z + ranGen.NextFloat(-spawnBounds.z / 2, spawnBounds.z / 2)) * 0.8f;
                    fishVels[index] = (internalPosition - transform.position).normalized;
                }
                else
                {
                    fishRotLeftTimes[index] -= deltaTime;
                    if (fishRotLeftTimes[index] <= 0)
                    {
                        fishVels[index]         = new Vector3(ranGen.NextFloat(-1f, 1f), 0, ranGen.NextFloat(-1f, 1f));
                        fishRotLeftTimes[index] = ranGen.NextFloat(1f, 5f);
                    }
                }
            }
Beispiel #18
0
        protected override void OnUpdate()
        {
            Entities.With(m_AddGroup).ForEach((Entity entity) =>
            {
                if (m_Random.NextFloat() > 0.1f)
                {
                    return;
                }

                EntityManager.GetComponentObject <Transform>(
                    EntityManager.GetComponentData <ViewReference>(entity).Value)
                .GetComponentInChildren <ReadyAudioPlayer>()
                .PlayAtPoint(EntityManager.GetComponentData <Translation>(entity).Value);
            });

            EntityManager.AddComponent(m_AddGroup, ComponentType.ReadWrite <AudioPlayed>());
            EntityManager.RemoveComponent(m_RemoveGroup, ComponentType.ReadWrite <AudioPlayed>());
        }
Beispiel #19
0
        /// <summary>
        /// Returns a random element with the chances of rolling based on <paramref name="weights"/>
        /// </summary>
        /// <param name="weights">Positive floats representing weights. Negative values may lead to unpredictable behaviour.</param>
        public static T GetRandom <T>(this IReadOnlyList <T> list, IReadOnlyList <float> weights, ref MRandom random)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }
            if (list.Count == 0)
            {
                throw new ArgumentException("Empty list");
            }
            if (weights == null)
            {
                throw new ArgumentNullException(nameof(weights));
            }
            if (weights.Count == 0)
            {
                throw new ArgumentException("Empty weights");
            }
            if (list.Count != weights.Count)
            {
                throw new ArgumentException("Array sizes must be equal");
            }

            if (list.Count == 1)
            {
                return(list[0]);
            }

            var cumulative = new List <float>(weights);

            for (int i = 1; i < cumulative.Count; i++)
            {
                cumulative[i] += cumulative[i - 1];
            }

            float randomValue = random.NextFloat(0, cumulative[cumulative.Count - 1]);
            int   index       = cumulative.FindIndex(a => a >= randomValue);

            if (index == -1)
            {
                throw new ArgumentException("Weights must be positive");
            }
            return(list[index]);
        }
Beispiel #20
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var time = Time.DeltaTime;

            timeSinceStart += time;
            var random = new Random((uint)(timeSinceStart * 1000f));

            return(Entities.WithBurst().ForEach((ref BugAiComponent ai, ref PhysicsVelocity velocity, in BugComponent bug) =>
            {
                ai.TimeTillNextTurn -= time;
                if (ai.TimeTillNextTurn <= 0)
                {
                    velocity.Angular = random.NextFloat3(ai.RotationRange.x, ai.RotationRange.y);
                    velocity.Angular = random.NextBool() ? velocity.Angular : -velocity.Angular;
                    ai.TimeTillNextTurn = random.NextFloat(ai.IntervalRangeSec.x, ai.IntervalRangeSec.y);
                }
            })
                   .Schedule(inputDeps));
        }
Beispiel #21
0
 //物理运算
 public void Execute(ref GravityComponentData gravityData, ref Position positionData)
 {
     if (gravityData.delay > 0)
     {
         gravityData.delay -= deltaTime;
     }
     else
     {
         Vector3 pos = positionData.Value;
         float   v   = gravityData.velocity + G * gravityData.mass * deltaTime;
         pos.y += v;
         if (pos.y < bottomY)
         {
             pos.y = topY;
             gravityData.velocity = 0f;
             gravityData.delay    = random.NextFloat(0, 10);
         }
         positionData.Value = pos;
     }
 }
Beispiel #22
0
 public static Color RandomColor(ref Random random, float alpha = 1)
 {
     return(new Color(random.NextFloat(), random.NextFloat(), random.NextFloat(), alpha));
 }
Beispiel #23
0
        private void Generate()
        {
            GameObject line = new GameObject();
            var        lr   = line.AddComponent <LineRenderer>();

            lr.positionCount = 5;
            lr.SetPosition(0, new Vector3(0, 0, -1));
            lr.SetPosition(1, new Vector3(m_world.pixelW, 0, -1));
            lr.SetPosition(2, new Vector3(m_world.pixelW, m_world.pixelH, -1));
            lr.SetPosition(3, new Vector3(0, m_world.pixelH, -1));
            lr.SetPosition(4, new Vector3(0, 0, -1));
            lr.startWidth = 2;
            lr.endWidth   = 2;

            for (int i = 0; i < m_world.settings.plates; i++)
            {
                int x = m_rand.NextInt(0, m_world.pixelW);
                int y = m_rand.NextInt(0, m_world.pixelH);

                Hex hex = m_layout.PixelToHex(new Point(x, y)).HexRound();

                Plate p = new Plate(this, hex, UnityEngine.Random.ColorHSV())
                {
                    elevation     = Random.Range(0f, 255f),
                    movementSpeed = m_rand.NextFloat(MIN_SPD, MAX_SPD),
                    direction     = (HexDirection)Random.Range(0, HexConstants.DIRECTIONS - 1),
                };
                m_world.AddPlate(p);
            }

            /*
             *  ------------------------------------------------------
             *      Setting hexes to plates
             *  ------------------------------------------------------
             */
            foreach (var pair in m_world.TileData)
            {
                int closestId = 0;
                int closest   = int.MaxValue;
                for (int i = 0; i < m_world.settings.plates; i++)
                {
                    int dist = pair.Key.Distance(m_world.plates[i].center);

                    if (closest > dist)
                    {
                        closest   = dist;
                        closestId = i;
                    }
                }
                for (int i = 0; i < m_world.settings.plates; i++)
                {
                    int dist = pair.Key.Distance(HexUtils.WrapOffset(m_world.plates[i].center, m_world.size.x));

                    if (closest > dist)
                    {
                        closest   = dist;
                        closestId = i;
                    }
                }
                pair.Value.hexData.plateId    = m_world.GetPlates()[closestId].id;
                pair.Value.hexData.oldPlateId = m_world.GetPlates()[closestId].id;
                m_world.GetPlates()[closestId].AddHex(pair.Key);
            }
        }
Beispiel #24
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            float  deltaTime           = Time.DeltaTime;
            uint   seed                = (uint)(UnityEngine.Random.value * 10000);
            Random random              = new Random(seed);
            var    entityCommandBuffer = _commandBufferSystem.CreateCommandBuffer().ToConcurrent();

            JobHandle jobHandle = Entities.ForEach(
                (Entity entity, int entityInQueryIndex, ref UnitSpawnerData spawnerData) =>
            {
                if (spawnerData._spawnInActive)
                {
                    return;
                }

                // Spawn Light Enemy Update Time
                if (spawnerData._currentLightUnitTime <= 0)
                {
                    if (spawnerData._currentLightEntityInBetweenTime <= 0)
                    {
                        float value = random.NextFloat();
                        if (value <= 0.5f)
                        {
                            entityCommandBuffer.Instantiate(entityInQueryIndex, spawnerData.lightEntityA);
                        }
                        else
                        {
                            entityCommandBuffer.Instantiate(entityInQueryIndex, spawnerData.lightEntityB);
                        }

                        spawnerData._currentLightEntityCount += 1;
                        if (spawnerData._currentLightEntityCount >= spawnerData.lightEntityBurstCount)
                        {
                            spawnerData._currentLightUnitTime = spawnerData
                                                                ._currentDeadPerSec
                                                                .Map(spawnerData.minDeathPerSec, spawnerData.maxDeathPerSec,
                                                                     spawnerData.maxTimeBetweenLightEntity, spawnerData.minTimeBetweenLightEntity);

                            spawnerData._currentLightEntityCount = 0;
                        }
                        else
                        {
                            spawnerData._currentLightEntityInBetweenTime = spawnerData.lightBurstTimeBetween;
                        }
                    }
                    else
                    {
                        spawnerData._currentLightEntityInBetweenTime -= deltaTime;
                    }
                }
                else
                {
                    spawnerData._currentLightUnitTime -= deltaTime;
                }

                // Spawn Heavy Enemy Update Time
                if (spawnerData._currentHeavyUnitTime <= 0)
                {
                    float value = random.NextFloat();
                    if (value <= 0.5f)
                    {
                        entityCommandBuffer.Instantiate(entityInQueryIndex, spawnerData.heavyEntityA);
                    }
                    else
                    {
                        entityCommandBuffer.Instantiate(entityInQueryIndex, spawnerData.heavyEntityB);
                    }

                    spawnerData._currentHeavyUnitTime = spawnerData
                                                        ._currentDeadPerSec
                                                        .Map(spawnerData.minDeathPerSec, spawnerData.maxDeathPerSec,
                                                             spawnerData.maxTimeBetweenHeavyEntity, spawnerData.maxTimeBetweenHeavyEntity);
                }
                else
                {
                    spawnerData._currentHeavyUnitTime -= deltaTime;
                }
            }).Schedule(inputDeps);

            _commandBufferSystem.AddJobHandleForProducer(jobHandle);

            return(jobHandle);
        }
Beispiel #25
0
            unsafe int UpdateCentroids()
            {
                int *hassign = stackalloc int[k];

                for (int i = 0; i < k; ++i)
                {
                    hassign[i] = 0;
                }

                Debug.Assert(centroids.Length == d * k);

                for (int i = 0; i < centroids.Length; ++i)
                {
                    centroids[i] = 0.0f;
                }

                for (int i = 0; i < numSamples; ++i)
                {
                    int ci = distances[i].index;
                    Debug.Assert(ci >= 0 && ci < k);
                    hassign[ci]++;
                    for (int j = 0; j < d; ++j)
                    {
                        centroids[ci * d + j] += features[i * d + j];
                    }
                }

                for (int ci = 0; ci < k; ci++)
                {
                    var ni = hassign[ci];
                    if (ni != 0)
                    {
                        for (int j = 0; j < d; ++j)
                        {
                            centroids[ci * d + j] /= (float)ni;
                        }
                    }
                }

                //
                // Take care of void clusters
                //

                int nsplit = 0;

                var random = new Unity.Mathematics.Random(1234);

                for (int ci = 0; ci < k; ++ci)
                {
                    //
                    // need to redefine a centroid
                    //

                    if (hassign[ci] == 0)
                    {
                        int cj = 0;
                        while (true)
                        {
                            //
                            // probability to pick this cluster for split
                            //

                            float p = (hassign[cj] - 1.0f) / (float)(numSamples - k);
                            float r = random.NextFloat();

                            if (r < p)
                            {
                                //
                                // found our cluster to be split
                                //
                                break;
                            }

                            cj = (cj + 1) % k;
                        }

                        for (int j = 0; j < d; ++j)
                        {
                            centroids[ci * d + j] = centroids[cj * d + j];
                        }

                        //
                        // small symmetric perturbation
                        //

                        float eps = 1.0f / 1024.0f;
                        for (int j = 0; j < d; ++j)
                        {
                            if (j % 2 == 0)
                            {
                                centroids[ci * d + j] *= 1 + eps;
                                centroids[cj * d + j] *= 1 - eps;
                            }
                            else
                            {
                                centroids[ci * d + j] *= 1 - eps;
                                centroids[cj * d + j] *= 1 + eps;
                            }
                        }

                        //
                        // assume even split of the cluster
                        //

                        hassign[ci]  = hassign[cj] / 2;
                        hassign[cj] -= hassign[ci];

                        nsplit++;
                    }
                }

                return(nsplit);
            }
        public static void CreateAttributeOperEntities(EntityManager EntityManager, Entity ActorEntity)
        {
            var random = new Unity.Mathematics.Random((uint)ActorEntity.Index);

            for (var i = 0; i < 5; i++)
            {
                new PermanentAttributeModifierTag().CreateAttributeModifier <TAttribute, TOper>(EntityManager, ActorEntity, random.NextFloat(0, 50));
            }
        }
        public MapResourceObject[] GenerateResources(Random rand, Terrain terrain, int size)
        {
            int featureSize = size / 16;
            int halfSize    = size / 2 - 16 / 2;

            MapResourceObject[] mapResourceObjects = new MapResourceObject[featureSize * featureSize];

            for (int z = 0; z < featureSize; z++)
            {
                for (int x = 0; x < featureSize; x++)
                {
                    uint index = rand.NextUInt(0, 5);

                    ItemObj[] resources;

                    switch (index)
                    {
                    default:
                        continue;

                    case 0:
                        resources = ironResources;
                        break;

                    case 1:
                        resources = copperResources;
                        break;

                    case 2:
                        resources = coalResources;
                        break;
                    }

                    if (resources.Length == 0)
                    {
                        continue;
                    }

                    ItemObj obj = resources[rand.NextInt(0, resources.Length)];

                    switch (obj.Item)
                    {
                    case MapResource resourceObject:
                    {
                        MapResourceObject instance = mapResourceObjects[x + z * featureSize] =
                            Instantiate(resourcePrefab, transform);
                        Vector3 pos = new Vector3(x * 16 - halfSize, 0, z * 16 - halfSize);
                        pos.y = terrain.SampleHeight(pos);

                        Quaternion rotation = Quaternion.Euler(0, rand.NextFloat(-180, 180), 0);

                        instance.Init(pos, rotation, obj.Item as MapResource, rand.NextUInt(3000, 6000));
                        break;
                    }

                    case Factory factory:

                        break;
                    }
                }
            }

            return(mapResourceObjects);
        }