Пример #1
0
    private void InitLaneData()
    {
        ResetData();

        var lane = SimulatorManager.Instance.MapManager.GetClosestLane(transform.position);

        laneSpeedLimit = lane.speedLimit;
        if (laneSpeedLimit > 0)
        {
            aggressionAdjustRate = laneSpeedLimit / 11.176f; // give more space at faster speeds
            stopHitDistance      = 12 / aggression * aggressionAdjustRate;
        }
        normalSpeed    = RandomGenerator.NextFloat(laneSpeedLimit, laneSpeedLimit + 1 + aggression);
        currentMapLane = lane;

        int     index   = -1;
        float   minDist = float.PositiveInfinity;
        Vector3 closest = Vector3.zero;

        // choose closest waypoint
        for (int i = 0; i < lane.mapWorldPositions.Count - 1; i++)
        {
            var p0 = lane.mapWorldPositions[i];
            var p1 = lane.mapWorldPositions[i + 1];

            var p = Utility.ClosetPointOnSegment(p0, p1, transform.position);

            float d = Vector3.SqrMagnitude(transform.position - p);
            if (d < minDist)
            {
                minDist = d;
                index   = i;
                closest = p;
            }
        }

        if (closest != lane.mapWorldPositions[index])
        {
            index++;
        }

        laneData      = new List <Vector3>(lane.mapWorldPositions);
        isDodge       = false;
        currentTarget = lane.mapWorldPositions[index];
        currentIndex  = index;

        stopTarget          = lane.mapWorldPositions[lane.mapWorldPositions.Count - 1];
        currentIntersection = lane.stopLine?.intersection;

        distanceToCurrentTarget = Vector3.Distance(new Vector3(frontCenter.position.x, 0f, frontCenter.position.z), new Vector3(currentTarget.x, 0f, currentTarget.z));
        distanceToStopTarget    = Vector3.Distance(new Vector3(frontCenter.position.x, 0f, frontCenter.position.z), new Vector3(stopTarget.x, 0f, stopTarget.z));

        if (currentIndex >= laneData.Count - 2)
        {
            StartStoppingCoroutine();
        }

        SetLastPosRot(transform.position, transform.rotation);
        isLaneDataSet = true;
    }
Пример #2
0
 public Plant(int id, Random random)
 {
     Id = id;
     X = random.NextFloat(0, 300f);
     Z = random.NextFloat(0, 300f);
     Species = AvailableSpecies[random.Next(0, AvailableSpecies.Length)];
 }
Пример #3
0
 public static Vector2 NextVector2(this Random self, Vector2 min, Vector2 max)
 {
     return(new Vector2(
                self.NextFloat(min.x, max.x),
                self.NextFloat(min.y, max.y)
                ));
 }
Пример #4
0
 public static Vector2 NextVector2(this Random self)
 {
     return(new Vector2(
                self.NextFloat(),
                self.NextFloat()
                ));
 }
Пример #5
0
 public AIKart(int kartNum, Level level, byte[][,] weight)
 {
     rand = new Random(kartNum);
     Level = level;
     Weight = weight;
     position = new Vector3(rand.NextFloat(-10, 11), rand.NextFloat(-10, 11), rand.NextFloat(-10, 11));
 }
Пример #6
0
        public static void StratifiedSample4D( float[] samples,
            int offset, int nx, int ny, int nu, int nv,
            bool jitter, Random random )
        {
            float dx = 1.0f / nx;
            float dy = 1.0f / ny;
            float du = 1.0f / nu;
            float dv = 1.0f / nv;

            int k = offset;
            for( int v = 0; v < nv; ++v )
            {
                for( int u = 0; u < nu; ++u )
                {
                    for( int y = 0; y < ny; ++y )
                    {
                        for( int x = 0; x < nx; ++x )
                        {
                            float jx = jitter ? random.NextFloat() : 0.5f;
                            float jy = jitter ? random.NextFloat() : 0.5f;
                            float ju = jitter ? random.NextFloat() : 0.5f;
                            float jv = jitter ? random.NextFloat() : 0.5f;

                            samples[ k ] = ( x + jx ) * dx;
                            samples[ k + 1 ] = ( y + jy ) * dy;
                            samples[ k + 2 ] = ( u + ju ) * du;
                            samples[ k + 3 ] = ( v + jv ) * dv;

                            k += 4;
                        }
                    }
                }
            }
        }
Пример #7
0
    public string GetName(GroundUnit unit, Theme theme = null)
    {
        string       name   = "NoValidThemeSet";
        List <Range> Ranges = new List <Range> ();

        if (theme == null)
        {
            float last  = 0;
            Theme lastT = null;
            foreach (Theme t in EmpireThemes.Keys)
            {
                if (lastT == null)
                {
                    last = 0;
                }
                Ranges.Add(new Range(last, last + EmpireThemes[t], t));
                lastT = t;
            }
            float roll = rnd.NextFloat(0, last);
            foreach (Range r in Ranges)
            {
                if (r.InRange(roll))
                {
                    lastT = r.theme;
                }
                //	name = ThemeManager.GetName (unit);
            }
        }
        else
        {
        }
        name = GroundUnitCounter + ". Mobile Infanterie";
        return(name);
    }
Пример #8
0
 public static Vector3 NextVector3(this Random self, Vector3 min, Vector3 max)
 {
     return(new Vector3(
                self.NextFloat(min.x, max.x),
                self.NextFloat(min.y, max.y),
                self.NextFloat(min.z, max.z)
                ));
 }
Пример #9
0
 public Animal(int id, Random random)
 {
     Id = id;
     X = random.NextFloat(0, 300f);
     Z = random.NextFloat(0, 300f);
     Species = AvailableSpecies[random.Next(0, AvailableSpecies.Length)];
     Name = $"{Species} {Id}";
 }
 public NebulaParameters(Random rng)
 {
     Color = rng.NextRandomColor();
     Offset = new Vector2(rng.Next(-1000, 1000), rng.Next(-1000, 1000));
     Falloff = rng.NextFloat(3, 6);
     Intensity = (float)(rng.NextDouble() * 0.2 + 1.0);
     Scale = rng.NextFloat(0.01f, 4f);
 }
Пример #11
0
 public static Color NextColor(this Random self)
 {
     return(new Color(
                self.NextFloat(),
                self.NextFloat(),
                self.NextFloat(),
                self.NextFloat()
                ));
 }
Пример #12
0
    public FogSphereSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      // Create a graphics screen. This screen has to call the FogSphereRenderer
      // to handle the FogSphereNode!
      _graphicsScreen = new DeferredGraphicsScreen(Services) { DrawReticle = true };
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // ----- Add a FogSphereNode to scene.
      var fogSphereNode = new FogSphereNode
      {
        Name = "FogSphere",
        ScaleLocal = new Vector3F(5, 3, 5),
        PoseWorld = new Pose(new Vector3F(0, 0, -3)),
      };
      _graphicsScreen.Scene.Children.Add(fogSphereNode);
    }
Пример #13
0
    public static Vector2 NextPointInsideCircle(this System.Random random)
    {
        // https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly/50746409#50746409
        float r     = Mathf.Sqrt(random.NextFloat());
        float theta = random.NextFloat() * 2 * Mathf.PI;
        float x     = Mathf.Cos(theta) * r;
        float y     = Mathf.Sin(theta) * r;

        return(new Vector2(x, y));
    }
Пример #14
0
 public PointerData(SharpDX.Direct2D1.DeviceContext context, uint id, PointerDeviceType type, Point p)
 {
     this.PointerId = id;
     this.DeviceType = type;
     this.Pointers = new List<Point>();
     this.Pointers.Add(p);
     Random rnd = new Random();
     // Colors of lines. presents in RGBA (a random value between 0.5 ~ 1.0)
     color = new Color4(rnd.NextFloat(0.5f, 1), rnd.NextFloat(0.5f, 1), rnd.NextFloat(0.5f, 1), 1);
 }
Пример #15
0
    public SpatialPartitionSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      GraphicsScreen.ClearBackground = true;
      GraphicsScreen.BackgroundColor = Color.Gray;
      GraphicsScreen.DrawReticle = true;
      SetCamera(new Vector3F(0, 1, 10), 0, 0);

      // Create a spatial partition. DigitalRune Geometry supports several types, see also
      // http://digitalrune.github.io/DigitalRune-Documentation/html/e32cab3b-cc7c-42ee-8ec9-23dd4467edd0.htm#WhichPartition
      // An AabbTree is useful for static objects. A DynamicAabbTree is good for moving objects.
      // The spatial partition can manage different types of items. In this case it manages
      // GeometricObjects. A delegate has to inform the spatial partition how to get the AABB
      // of an object.
      //_spatialPartition = new DynamicAabbTree<GeometricObject>
      _spatialPartition = new AabbTree<GeometricObject>
      {
        GetAabbForItem = geometricObject => geometricObject.Aabb,

        // Optional: The tree is automatically built using a mixed top-down/bottom-up approach. 
        // Bottom-up building is slower but produces better trees. If the tree building takes too 
        // long, we can lower the BottomUpBuildThreshold (default is 128).
        //BottomUpBuildThreshold = 0,

        // Optional: A filter can be set to disable certain kind of overlaps.
        //Filter = ...
      };

      // Create a triangle mesh.
      var triangleMesh = new SphereShape(1).GetMesh(0.01f, 4);
      var triangleMeshShape = new TriangleMeshShape(triangleMesh)
      {
        // TriangleMeshShapes can also use a spatial partition to manage triangle.
        // The items in the spatial partition are the triangle indices. The GetAabbForItem
        // delegate is set automatically.
        Partition = new AabbTree<int>(),
      };

      // Spatial partitions are built automatically when needed. However, it is still recommended
      // to call Update to initialize the spatial partition explicitly.
      triangleMeshShape.Partition.Update(false);

      // Add a lot of triangle mesh objects to _spatialPartition.
      var random = new Random();
      for (int i = 0; i < 50; i++)
      {
        var randomPosition = new Vector3F(random.NextFloat(-6, 6), random.NextFloat(-3, 3), random.NextFloat(-10, 0));
        var geometricObject = new GeometricObject(triangleMeshShape, new Pose(randomPosition));
        _spatialPartition.Add(geometricObject);
      }

      _spatialPartition.Update(false);
    }
Пример #16
0
 public static string[] generate_input_file_content(int seed)
 {
     string[] data = new string[2];
     Random rand = new Random(seed);
     string operation = rand.Next(0, 4).ToString();
     string num0 = rand.NextFloat().ToString();
     string num1 = rand.NextFloat().ToString();
     data[0] = operation;
     data[1] = num0 + " " + num1;
     return data;
 }
Пример #17
0
    public SkySample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));

      // The DynamicSkyObject creates the dynamic sky and lights.
      GameObjectService.Objects.Add(new DynamicSkyObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Add a grain filter to add some noise in the night.
      _graphicsScreen.PostProcessors.Add(new GrainFilter(GraphicsService)
      {
        IsAnimated = true,
        LuminanceThreshold = 0.3f,
        ScaleWithLuminance = true,
        Strength = 0.04f,
        GrainScale = 1.5f,
      });
    }
Пример #18
0
    public void SetName(string _name)
    {
        var rnd = new System.Random(_name.GetHashCode());

        logger.Trace("Kingdom " + GetDebugSignature() + " is now named [" + _name + "]");
        name  = _name;
        color = Color.FromHSV(
            rnd.NextFloat(),
            rnd.NextFloat() / 3f + 0.3f,
            rnd.NextFloat() / 5f + 0.5f
            );
    }
Пример #19
0
    public SplitScreenSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new SplitScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera of player A.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      var projection = (PerspectiveProjection)cameraGameObject.CameraNode.Camera.Projection;
      projection.SetFieldOfView(
        projection.FieldOfViewY,
        GraphicsService.GraphicsDevice.Viewport.AspectRatio / 2,
        projection.Near,
        projection.Far);
      cameraGameObject.CameraNode.Camera = new Camera(projection);

      // A second camera for player B.
      _cameraNodeB = new CameraNode(cameraGameObject.CameraNode.Camera);
      _graphicsScreen.ActiveCameraNodeB = _cameraNodeB;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }
    }
Пример #20
0
 public const float TimeBetweenRolls = 5;     //in turns
 public void RollMaint()
 {
     TimeSinceLastRoll += 1;
     if (TimeSinceLastRoll > TimeBetweenRolls - .1 * MaintClock)
     {
         TimeSinceLastRoll = 0f;
         if (random.NextFloat(0f, 1f) < EffectiveFailRate)
         {
             TakeInternalHit(MaintDamage);
         }
     }
 }
Пример #21
0
        public static Vector3 NextUnitVector3(this Random self)
        {
            var theta = self.NextFloat() * 2.0f * Mathf.PI;
            var omega = self.NextFloat() * 2.0f * Mathf.PI;
            var t     = Mathf.Acos(omega * (1.0f / Mathf.PI) - 1.0f);

            return(new Vector3(
                       Mathf.Sin(t) * Mathf.Cos(theta),
                       Mathf.Sin(t) * Mathf.Sin(theta),
                       Mathf.Cos(t)
                       ));
        }
Пример #22
0
        static IEnumerator GeneratePoints(Graph graph, WorldGeneratorData data, WorldGeneratorOptions options)
        {
            var pointRandomizer = new System.Random(data.Randomizer.Next());

            data.Points = new List <Vector2f>();
            for (var i = 0; i < options.PointCount; i++)
            {
                data.Points.Add(new Vector2f(
                                    pointRandomizer.NextFloat(0, 1),
                                    pointRandomizer.NextFloat(0, 1)));
                yield return(null);
            }
        }
Пример #23
0
        public void CeilingTest()
        {
            const int max = 1000;

            var r = new Random(987);

            for (var i = 0; i < 30; i++)
            {
                var v = new Vector2(r.NextFloat() * max, r.NextFloat() * max);
                var c = v.Ceiling();
                Assert.AreEqual(Math.Ceiling(v.X), c.X);
                Assert.AreEqual(Math.Ceiling(v.Y), c.Y);
            }
        }
Пример #24
0
        public void Vector2Test()
        {
            Vector2 value = new Vector2(rnd.NextFloat(), rnd.NextFloat());

            stream.Skip(1);
            stream.WriteVector2(value);

            Assert.AreEqual(65, stream.BitOffset);
            stream.ResetRead();
            stream.Skip(1);

            Assert.AreEqual(value, stream.ReadVector2());
            Assert.AreEqual(65, stream.BitOffset);
        }
Пример #25
0
        public void FloorTest()
        {
            const int max = 1000;

            var r = new Random(102);

            for (var i = 0; i < 30; i++)
            {
                var v = new Vector2(r.NextFloat() * max, r.NextFloat() * max);
                var c = v.Floor();
                Assert.AreEqual(Math.Floor(v.X), c.X);
                Assert.AreEqual(Math.Floor(v.Y), c.Y);
            }
        }
Пример #26
0
        public static Vector2 NextVector2(this System.Random rand, float minLength, float maxLength)
        {
            double theta  = rand.NextDouble() * 2 * Math.PI;
            float  length = rand.NextFloat(minLength, maxLength);

            return(new Vector2(length * (float)Math.Cos(theta), length * (float)Math.Sin(theta)));
        }
Пример #27
0
        private void FireWeapon(TargetTuple target, Vector3 displacement, bool isServer)
        {
            // sound
            _source.PlayOneShot(_shotSound, _shotVolume);
            // particle
            _shotEffect.Play();

            if (_muzzleFlashEffect != null)
            {
                _muzzleFlashEffect.Play();
            }

            if (isServer)
            {
                if (target.IsUnit)
                {
                    float roll = _random.NextFloat(0.0, 100.0);
                    // HIT
                    if (roll <= _data.Accuracy)
                    {
                        Debug.LogWarning("Cannon shell dispersion is not implemented yet");
                        target.Enemy.HandleHit(_data.Damage, displacement, null);
                    }
                }
                else
                {
                    // TODO: fire pos damage not implemented
                }
            }
        }
Пример #28
0
    /// <summary>
    /// Generates a random point inside the circle with specified radius.
    /// </summary>
    public static Point InCircleGetPoint(this Random r, float radius = 1f)
    {
        var   num   = radius * (float)Math.Sqrt(r.NextFloat(0, 1));
        float f     = RandomAngleRadians(r);
        var   point = new Point((num * (float)(Math.Cos(f))) + 1500, (num * (float)(Math.Sin(f)) + 1500));

        return(point);
    }
Пример #29
0
 /// <summary>
 /// Returns a random element from the given set.
 /// </summary>
 static public T Choose <T>(this Random inRandom, WeightedSet <T> inChoices)
 {
     if (inChoices.Count == 0)
     {
         throw new IndexOutOfRangeException();
     }
     return(inChoices.GetItemNormalized(inRandom.NextFloat()));
 }
Пример #30
0
        public static Vector2 NextUnitVector2(this Random self)
        {
            var angle = self.NextFloat() * 2.0f * Mathf.PI;

            return(new Vector2(
                       Mathf.Cos(angle),
                       Mathf.Sin(angle)
                       ));
        }
Пример #31
0
        public void ResultContentTest()
        {
            List<float> data = new List<float>();
            Random rand = new Random();
            data.Add(rand.NextFloat());
            data.Add(rand.NextFloat());
            string[] time = new string[2];
            time[0] = "00:00:02";
            time[1] = "00:00:02";
            Writer.create_result_file(ContentGenerator.generate_result_file_content(data,time));
            string[] testdata = File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "Data//Result//Result.dat"));
            for (int i = 0; i < testdata.Length; i++)
            {
                Debug.WriteLine(testdata[i]);
            }

            Assert.IsTrue(testdata.Length == 6);
        }
Пример #32
0
    private Vector3 RandomSpawnPoint()
    {
        if (_randomGenerator.NextBoolean())
        {
            bool  isRight = _randomGenerator.NextBoolean();
            float x       = isRight ? SPAWN_DISTANCE_X_MIN : SPAWN_DISTANCE_X_MAX;

            float y = _randomGenerator.NextFloat(SPAWN_DISTANCE_Y_MIN, SPAWN_DISTANCE_Y_MAX);
            return(new Vector3(x, y));
        }
        else
        {
            bool  isTop = _randomGenerator.NextBoolean();
            float y     = isTop ? SPAWN_DISTANCE_Y_MAX : SPAWN_DISTANCE_Y_MIN;

            float x = _randomGenerator.NextFloat(SPAWN_DISTANCE_X_MIN, SPAWN_DISTANCE_X_MAX);
            return(new Vector3(x, y));
        }
    }
Пример #33
0
        public static void GenerateHomePositions(int n)
        {
            Random rand = new Random();
            bool passed = false;
            Vector2 randPosition = new Vector2(0, 0);

            int i = 0;
            foreach(Team team in TeamManager.teams)
            {
                passed = false;
                while (!passed)
                {
                    randPosition = new Vector2(rand.NextFloat(LevelSpawner.BorderMargin.X + radius, GameRoot.ScreenSize.X - LevelSpawner.BorderMargin.X - 2 * radius), rand.NextFloat(LevelSpawner.BorderMargin.Y + radius, GameRoot.ScreenSize.Y - LevelSpawner.BorderMargin.Y - 2 * radius));
                    if (i == 0)
                    {
                        float distance = Vector2.DistanceSquared(randPosition, GameRoot.ScreenSize * 0.5f);
                        if(distance < (0.5f * GameRoot.ScreenSize.Y * 0.5f * GameRoot.ScreenSize.Y))
                            passed = false;
                        else
                            passed = true;
                    }

                    else
                    {
                        for (int j = 0; j < i; j++)
                        {
                            float distance = Vector2.DistanceSquared(randPosition, TeamManager.teams[j].homePlanet.Position);
                            if (distance < (1.5f * GameRoot.ScreenSize.X / n) * (1.5f * GameRoot.ScreenSize.X / n))
                            {
                                passed = false;
                                break;
                            }
                            else
                                passed = true;
                        }
                    }
                }

                team.homePlanet = new Planet(randPosition, team.Color, 1.0f, i, team);
                team.planetsColonized.Add(team.homePlanet);
                i++;
            }
        }
Пример #34
0
 static void MutateShape( Random rand, DNA dna, Shape shape, TaskState task )
 {
     int maxOverlap = task.ProjectOptions.MaxOverlap;
     shape.PreviousState = shape.Clone() as Shape;
     switch( rand.Next( 9 ) ) {
         case 0:
             shape.Color = Color.FromArgb( (byte)rand.Next( task.ProjectOptions.MinAlpha, 256 ), shape.Color.R,
                                           shape.Color.G, shape.Color.B );
             dna.LastMutation = MutationType.ReplaceColor;
             break;
         case 1:
             shape.Color = Color.FromArgb( shape.Color.A, (byte)rand.Next( 256 ), shape.Color.G, shape.Color.B );
             dna.LastMutation = MutationType.ReplaceColor;
             break;
         case 2:
             shape.Color = Color.FromArgb( shape.Color.A, shape.Color.R, (byte)rand.Next( 256 ), shape.Color.B );
             dna.LastMutation = MutationType.ReplaceColor;
             break;
         case 3:
             shape.Color = Color.FromArgb( shape.Color.A, shape.Color.R, shape.Color.G, (byte)rand.Next( 256 ) );
             dna.LastMutation = MutationType.ReplaceColor;
             break;
         case 4:
         case 5:
             shape.Points[rand.Next( shape.Points.Length )].X = rand.NextFloat( -maxOverlap,
                                                                                task.ImageWidth + maxOverlap );
             dna.LastMutation = MutationType.ReplacePoint;
             break;
         case 6:
         case 7:
             shape.Points[rand.Next( shape.Points.Length )].Y = rand.NextFloat( -maxOverlap,
                                                                                task.ImageHeight + maxOverlap );
             dna.LastMutation = MutationType.ReplacePoint;
             break;
         case 8:
             shape.Points[rand.Next( shape.Points.Length )].X = rand.NextFloat( -maxOverlap,
                                                                                task.ImageWidth + maxOverlap );
             shape.Points[rand.Next( shape.Points.Length )].Y = rand.NextFloat( -maxOverlap,
                                                                                task.ImageHeight + maxOverlap );
             dna.LastMutation = MutationType.ReplacePoints;
             break;
     }
 }
Пример #35
0
        public Box(int _screenW, int _screenH, Random _rndRandom)
            : base()
        {
            screenW = _screenW;
              screenH = _screenH;

              rnd = _rndRandom;

              x = randomBetween(0, screenW);
              y = randomBetween(0, screenH);
              width = randomBetween(10, 50);
              height = randomBetween(10, 50);
              speed = randomBetween(50, 250);
              dirX = rnd.NextFloat() < 0.5d ? -1 : 1;
              dirY = rnd.NextFloat() < 0.5d ? -1 : 1;

              aabb = new AABB();
              updateAABB();
        }
        public DNA Initialize( Random rand, TaskState task )
        {
            DNA dna = new DNA {
                Shapes = new Shape[task.Shapes]
            };
            int shapesPerSegment = task.Shapes / 9;
            int shapeCounter = 0;

            for( int i = 0; i < task.Shapes - shapesPerSegment * 9; i++ ) {
                Shape shape = new Shape {
                    Color = Color.FromArgb( StartingAlpha, Color.R, Color.G, Color.B ),
                    Points = new PointF[task.Vertices]
                };
                for( int j = 0; j < shape.Points.Length; j++ ) {
                    shape.Points[j] = new PointF( rand.NextFloat( -MaxOverlap, task.ImageWidth + MaxOverlap ),
                                                  rand.NextFloat( -MaxOverlap, task.ImageHeight + MaxOverlap ) );
                }
                dna.Shapes[i] = shape;
                shapeCounter++;
            }

            for( int x = 0; x < 3; x++ ) {
                for( int y = 0; y < 3; y++ ) {
                    for( int i = 0; i < shapesPerSegment; i++ ) {
                        Shape shape = new Shape {
                            Color = Color.FromArgb( StartingAlpha, Color.R, Color.G, Color.B ),
                            Points = new PointF[task.Vertices]
                        };
                        for( int j = 0; j < shape.Points.Length; j++ ) {
                            shape.Points[j] =
                                new PointF(
                                    rand.NextFloat( task.ImageWidth / 3f * x - MaxOverlap,
                                                    task.ImageWidth / 3f * ( x + 1 ) + MaxOverlap ),
                                    rand.NextFloat( task.ImageHeight / 3f * y - MaxOverlap,
                                                    task.ImageHeight / 3f * ( y + 1 ) + MaxOverlap ) );
                        }
                        dna.Shapes[shapeCounter] = shape;
                        shapeCounter++;
                    }
                }
            }
            return dna;
        }
Пример #37
0
 /// <summary>
 /// Given nx strata in [0,1],
 /// Place a sample in each one,
 /// starting from samples[ offset ]
 /// and ending at samples[ offset + nx - 1 ]
 /// </summary>
 /// <param name="samples"></param>
 /// <param name="jitter"></param>
 public static void StratifiedSample1D( float[] samples,
     int offset, int nx,
     bool jitter, Random random )
 {
     float invTot = 1.0f / nx;
     for( int i = 0; i < nx; ++i )
     {
         float j = jitter ? random.NextFloat() : 0.5f;
         samples[ offset + i ] = ( i + j ) * invTot;
     }
 }
Пример #38
0
    private Color GenerateSimilarColor(Color color)
    {
        Color newColor;
        float h, s, v;

        Color.RGBToHSV(color, out h, out s, out v);
        do
        {
            // vary s and v a little bit but keep h.
            float new_s = Mathf.Clamp01(s + RandomGenerator.NextFloat(-0.25f, 0.25f));
            float new_v = Mathf.Clamp01(v + RandomGenerator.NextFloat(-0.25f, 0.25f));
            newColor = Color.HSVToRGB(h, new_s, new_v);
        } while (!InstanceColorSet.Add(newColor));
        // TODO: There is a possibility that all possible colors have been generated,
        // which will cause infinite loop here. But since we have at least 128 * 128 = 16384
        // possible differen colors for each hue, it is very unlikely that we generate
        // all possible colors.
        // We may improve the logic later to fully avoid infinite loop.

        return(newColor);
    }
Пример #39
0
    public override void GetTransform(PropSocket socket, DungeonModel model, Matrix4x4 propTransform, System.Random random, out Vector3 outPosition, out Quaternion outRotation, out Vector3 outScale)
    {
        base.GetTransform(socket, model, propTransform, random, out outPosition, out outRotation, out outScale);

        var angle    = random.NextFloat() * 360;
        var rotation = Quaternion.Euler(0, angle, 0);

        outRotation = rotation;

        var variation = new Vector3(0.25f, -1, 0.25f);

        outPosition = Vector3.Scale(random.OnUnitSphere(), variation);
    }
Пример #40
0
        /// <summary>
        /// Given nx x ny strata in [0,1]^2
        /// Place a sample in each one,
        /// starting at samples[ offset ],
        /// and ending at samples[ offset + nx * ny - 1 ]
        /// </summary>
        /// <param name="samples"></param>
        /// <param name="jitter"></param>
        public static void StratifiedSample2D( float[] samples,
            int offset, int nx, int ny,
            bool jitter, Random random )
        {
            float dx = 1.0f / nx;
            float dy = 1.0f / ny;

            int k = offset;
            for( int y = 0; y < ny; ++y )
            {
                for( int x = 0; x < nx; ++x )
                {
                    float jx = jitter ? random.NextFloat() : 0.5f;
                    float jy = jitter ? random.NextFloat() : 0.5f;

                    samples[ k ] = ( x + jx ) * dx;
                    samples[ k + 1 ] = ( y + jy ) * dy;

                    k += 2;
                }
            }
        }
Пример #41
0
        public void Load()
        {
            _program = _assets.Fetch<ShaderProgram>("Main");
            _vbo = new VBO();
            _tex = _assets.Fetch<Texture>("star.png");
            data = new List<Vertex>();
            var rnd = new Random();
            for (var i = 0; i < 150; i++)
            {
                //rnd.NextDouble()

                var x = rnd.NextFloat(-80f, 80f);
                var y = rnd.NextFloat(-80f, 80f);

                var z = rnd.NextFloat(0f, 10f) - 60.0f;
                AddStar((float)rnd.NextDouble() + 0.1f, new Vector3(x, y,z));
            }

            _vbo.Buffer(data.ToArray());
            _vao = new VAO(_program, _vbo);
            Loaded = true;
        }
Пример #42
0
        public static object Next(this System.Random generator, Type desired)
        {
            switch (Type.GetTypeCode(desired))
            {
            case TypeCode.Boolean:
                return(generator.NextBool());

            case TypeCode.Byte:
                return(generator.NextByte());

            case TypeCode.Char:
                return(generator.NextChar());

            case TypeCode.DateTime:
                return(generator.NextDateTime());

            case TypeCode.Decimal:
                return(generator.NextDecimal());

            case TypeCode.Double:
                return(generator.NextDouble());

            case TypeCode.Int16:
                return(generator.NextShort());

            case TypeCode.Int32:
                return(generator.NextInt());

            case TypeCode.Int64:
                return(generator.NextLong());

            case TypeCode.SByte:
                return(generator.NextSByte());

            case TypeCode.Single:
                return(generator.NextFloat());

            case TypeCode.UInt16:
                return(generator.NextUShort());

            case TypeCode.UInt32:
                return(generator.NextUInt());

            case TypeCode.UInt64:
                return(generator.NextULong());

            default:
                throw new ArgumentOutOfRangeException("Cannot provide a random " + desired);
            }
        }
Пример #43
0
        public void NextFloatTest()
        {
            var r = new Random(555);
            var last = 0f;

            for (var i = 0; i < 20; i++)
            {
                var f = r.NextFloat();
                Assert.AreNotEqual(last, f);
                Assert.Less(f, 1f);
                Assert.GreaterOrEqual(f, 0f);
                last = f;
            }
        }
Пример #44
0
        static IEnumerator GenerateHeightMap(Graph graph, WorldGeneratorData data, WorldGeneratorOptions options)
        {
            var heightMapRandom = new System.Random(data.Randomizer.Next());
            var queue           = new Queue <Corner>();

            for (int c = 0; c < graph.Corners.Count; c++)
            {
                var corner = graph.Corners[c];
                //Borders are always ocean
                if (corner.IsBorder)
                {
                    corner.Elevation = 0;
                    //Add all the borders to the processing queue and work inward
                    queue.Enqueue(corner);
                }
                else
                {
                    //treating PositiveInfinity as unset
                    corner.Elevation = float.PositiveInfinity;
                }

                yield return(null);
            }

            while (queue.Any())
            {
                var corner = queue.Dequeue();
                foreach (var neighbor in corner.Neighbors)
                {
                    //always increase slightly to prevent reprocessing
                    var newElevation = corner.Elevation + 0.01f;

                    //increase by random amount if travelling over land
                    if (!corner.Biome.IsWater && !neighbor.Biome.IsWater)
                    {
                        newElevation += heightMapRandom.NextFloat(1, 2);
                    }

                    //TODO: find way to improve this, could cause a lot of reprocessing
                    if (newElevation < neighbor.Elevation)
                    {
                        neighbor.Elevation = newElevation;
                        queue.Enqueue(neighbor);
                    }
                }

                yield return(null);
            }
        }
 public void RecieveDamage(float f)
 {
     if (rand.NextFloat(0, 1) > (NumberTroops * 1.25 + 1) / MaxNumberTroops)
     {
         Commander.InjureGroundCombat(Location, this, f / (NumberTroops + 1));
     }
     NumberTroops -= (int)System.Math.Floor((f / HealthPerTroop));
     if (NumberTroops <= 0)
     {
         float leftovers = (0 - NumberTroops) * HealthPerTroop;
         Commander.InjureGroundCombat(Location, this, leftovers);
         NumberTroops = 0;
     }
     UpdateStatus();
 }
Пример #46
0
        public StratifiedND( Random random, params int[] nSamples )
        {
            nDimensions = nSamples.Length;

            this.nSamples = new int[ nDimensions ];
            Array.Copy( nSamples, this.nSamples, nSamples.Length );

            int nSamplesTotal = NumSamplesTotal;
            int nFloatsTotal = nSamplesTotal * nDimensions;
            values = new float[ nFloatsTotal ];
            for( int i = 0; i < nFloatsTotal; ++i )
            {
                values[ i ] = random.NextFloat();
            }
        }
Пример #47
0
        public UpdateOutcome Update(Random random)
        {
            if (random.NextDouble() < 0.05)
            {
                Health = Math.Max(0f, Math.Min(Health + random.NextFloat(-0.1f, 0.1f), 1f)); // chance of varying up to 10% of our health

                // Dead?
                if (Health <= 0f)
                    return UpdateOutcome.Removed;

                return UpdateOutcome.Changed;
            }

            return UpdateOutcome.None;
        }
Пример #48
0
		/// <summary>
		/// Initialize services :
		/// </summary>
		protected override void Initialize ()
		{
			base.Initialize();

			LoadContent();
			Reloading += (s,e) => LoadContent();

			CreateTargets();
			GraphicsDevice.DisplayBoundsChanged += (s,e) => CreateTargets();


			var lr = GetService<LightRenderer>();
			var rand = new Random(542);
			
			for (int i=0; i<1024; i++) {
				var light = new OmniLight();
				light.RadiusOuter	=	rand.NextFloat(3, 4);
				light.RadiusInner	=	light.RadiusOuter * 0.5f;
				light.Position		=	rand.NextVector3( new Vector3(-50,3,-50), new Vector3(50,6,50) );
				//light.Position		=	Vector3.Up * 3; //new Vector3(10,2,20);
				//light.Position		=	new Vector3( (i/32)*3-48, 2.5f, (i%32)*3-48 );
				light.Intensity		=	rand.NextColor4()*50;// new Color4(10,10,5,0);
				lr.OmniLights.Add( light );
			}

			var names = spotAtlas.SubImageNames;

			lr.MaskAtlas	=	spotAtlas;

			for (int i=0; i<16; i++) {
				var light = new SpotLight();

				var position		=	rand.NextVector3( new Vector3(-30,20,-30), new Vector3(30,20,30) );
				var target			=	position + rand.NextVector3( new Vector3(-10, -35,-10), new Vector3(10, -35,10) );

				//position			=	rand.NextVector3( new Vector3(-50,50,-50), new Vector3(50,50,50) );
				//target				=	Vector3.Down * 20;

				light.Intensity		=	rand.NextColor4()*100;// new Color4(10,10,5,0);
				light.SpotView		=	Matrix.LookAtRH( position, target, Vector3.Up );
				light.RadiusOuter	=	(target - position).Length() * 1.5f;
				light.RadiusInner	=	light.RadiusOuter * 0.5f;
				light.MaskName		=	names[ rand.Next(0, names.Length) ];
				light.Projection	=	Matrix.PerspectiveFovRH( MathUtil.DegreesToRadians(45), 1, 1f, light.RadiusOuter );

				lr.SpotLights.Add( light );
			}
		}
Пример #49
0
		/// <summary>
		/// Add services :
		/// </summary>
		protected override void Initialize ()
		{
			
			//	initialize services :
			base.Initialize();

			//	create structured buffers and shaders :
			buffer1		=	new StructuredBuffer( GraphicsDevice, typeof(Vector2), NumberOfElements  , StructuredBufferFlags.None );
			buffer2		=	new StructuredBuffer( GraphicsDevice, typeof(Vector2), NumberOfElements  , StructuredBufferFlags.None );
			paramsCB	=	new ConstantBuffer( GraphicsDevice, typeof(Params) );
			shader		=	Content.Load<Ubershader>("test");
			factory		=	new StateFactory( shader, typeof(ShaderFlags), Primitive.TriangleList, VertexInputElement.Empty );

			//
			//	Create and write data :
			//
			var	rand	=	new Random();
			var	input	=	Enumerable.Range(0, NumberOfElements).Select( i => new Vector2( rand.NextFloat(0,100), i ) ).ToArray();
			buffer1.SetData( input );
			
			//	add keyboard handler :
			InputDevice.KeyDown += InputDevice_KeyDown;
		}
Пример #50
0
 private IEnumerator ChangePedState()
 {
     return(IdleAnimation(RandomGenerator.NextFloat(idleTime * 0.5f, idleTime)));
 }
Пример #51
0
 public static Vector2 GenerateRandomVector2(Random random, Range horizontalRange, Range verticalRange)
 {
     return new Vector2(random.NextFloat(horizontalRange.Min, horizontalRange.Max), random.NextFloat(verticalRange.Min, verticalRange.Max));
 }
Пример #52
0
 public static Vector2 GenerateRandomUnitVector2(Random random)
 {
     float radians = random.NextFloat(-FlaiMath.Pi, FlaiMath.Pi);
     return FlaiMath.GetAngleVector(radians);
 }
Пример #53
0
 /// <summary>
 /// Returns a random vector between the given vectors.
 /// </summary>
 static public Vector2 NextVector2(this Random inRandom, Vector2 inStart, Vector2 inEnd)
 {
     return(new Vector2(inRandom.NextFloat(inStart.x, inEnd.x), inRandom.NextFloat(inStart.y, inEnd.y)));
 }
Пример #54
0
    private void SetNeededComponents()
    {
        rb           = GetComponent <Rigidbody>();
        allRenderers = GetComponentsInChildren <Renderer>().ToList();
        allLights    = GetComponentsInChildren <Light>();
        if (allLights.Length == 0)
        {
            Debug.LogError(gameObject.name + " did not find any lights!");
        }

        Color.RGBToHSV(NPCColor, out float h, out float s, out float v);
        h        = Mathf.Clamp01(RandomGenerator.NextFloat(h - 0.01f, h + 0.01f));
        v        = Mathf.Clamp01(RandomGenerator.NextFloat(v - 0.1f, v + 0.1f));
        NPCColor = Color.HSVToRGB(h, s, v);

        MainCollider = GetComponentInChildren <MeshCollider>();

        // wheel collider holder
        wheelColliderHolder = new GameObject("WheelColliderHolder");
        wheelColliderHolder.transform.SetParent(transform.GetChild(0));
        wheelColliderHolder.SetActive(true);

        foreach (Renderer child in allRenderers)
        {
            if (child.name.Contains("Wheel") && !child.name.Contains("Spare"))
            {
                AddWheel(child.transform);
            }

            if (child.name.Contains("Body"))
            {
                var rendererMats = child.materials;
                for (int i = 0; i < rendererMats.Length; i++)
                {
                    if (rendererMats[i].name.Contains("Body"))
                    {
                        rendererMats[i].SetColor("_BaseColor", NPCColor);
                    }
                }
                if (MainCollider == null)
                {
                    MainCollider        = child.gameObject.AddComponent <MeshCollider>();
                    MainCollider.convex = true;
                }
            }
            {
                var rendererMats = child.materials;
                for (int i = 0; i < rendererMats.Length; i++)
                {
                    if (rendererMats[i].name.Contains("LightHead"))
                    {
                        headLight = new IndicatorRenderer()
                        {
                            renderer = child, materialIndex = i
                        }
                    }
                    ;
                    if (rendererMats[i].name.Contains("LightBrake"))
                    {
                        brakeLight = new IndicatorRenderer()
                        {
                            renderer = child, materialIndex = i
                        }
                    }
                    ;
                    if (rendererMats[i].name.Contains("IndicatorLeft"))
                    {
                        indicatorLeft = new IndicatorRenderer()
                        {
                            renderer = child, materialIndex = i
                        }
                    }
                    ;
                    if (rendererMats[i].name.Contains("IndicatorRight"))
                    {
                        indicatorRight = new IndicatorRenderer()
                        {
                            renderer = child, materialIndex = i
                        }
                    }
                    ;
                    if (rendererMats[i].name.Contains("IndicatorReverse"))
                    {
                        indicatorReverse = new IndicatorRenderer()
                        {
                            renderer = child, materialIndex = i
                        }
                    }
                    ;
                }
            }
        }

        MainCollider.enabled          = true;
        MainCollider.gameObject.layer = LayerMask.NameToLayer("NPC");

        foreach (Light light in allLights)
        {
            if (light.name.Contains("Head"))
            {
                headLights.Add(light);
            }
            else if (light.name.Contains("Brake"))
            {
                brakeLights.Add(light);
            }
            else if (light.name.Contains("IndicatorLeft"))
            {
                indicatorLeftLights.Add(light);
            }
            else if (light.name.Contains("IndicatorRight"))
            {
                indicatorRightLights.Add(light);
            }
            else if (light.name.Contains("IndicatorReverse"))
            {
                indicatorReverseLight = light;
            }
        }

        if (headLights.Count == 0)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing light 'Head'");
        }
        if (brakeLights.Count == 0)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing light 'Brake'");
        }
        if (indicatorLeftLights.Count == 0)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing light 'IndicatorLeft'");
        }
        if (indicatorRightLights.Count == 0)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing light 'IndicatorRight'");
        }
        if (indicatorReverseLight == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing light 'IndicatorReverse'");
        }
        if (MainCollider == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing renderer 'Body'");
        }
        if (headLight == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing material 'LightHead'");
        }
        if (brakeLight == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing material 'LightBrake'");
        }
        if (indicatorRight == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing material 'IndicatorRight'");
        }
        if (indicatorLeft == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing material 'IndicatorLeft'");
        }
        if (indicatorReverse == null)
        {
            Debug.LogWarning($"Asset {gameObject.name} missing material 'IndicatorReverse'");
        }

        Bounds = new Bounds(transform.position, Vector3.zero);
        foreach (Renderer renderer in allRenderers)
        {
            Bounds.Encapsulate(renderer.bounds); // renderer.bounds is world space
        }

        // centerOfMass is relative to the transform origin
        if (wheels.Count < 4 || name.Contains("Trailer"))
        {
            rb.centerOfMass = Bounds.center + new Vector3(0, -Bounds.extents.y * 0.15f, 0);
        }
        else
        {
            rb.centerOfMass = Bounds.center + new Vector3(0, 0, Bounds.extents.z * 0.3f);
        }

        // GroundTruth Box Collider
        var gtBox         = new GameObject("GroundTruthBox");
        var gtBoxCollider = gtBox.AddComponent <BoxCollider>();

        gtBoxCollider.isTrigger = true;
        gtBoxCollider.size      = Bounds.size;
        gtBoxCollider.center    = new Vector3(Bounds.center.x, Bounds.center.y, Bounds.center.z);
        gtBox.transform.parent  = transform;
        gtBox.layer             = LayerMask.NameToLayer("GroundTruth");

        // front transforms
        GameObject go = new GameObject("Front");

        go.transform.position = new Vector3(Bounds.center.x, Bounds.min.y + 0.5f, Bounds.center.z + Bounds.max.z);
        go.transform.SetParent(transform, true);
        frontCenter           = go.transform;
        go                    = new GameObject("FrontHigh");
        go.transform.position = new Vector3(Bounds.center.x, Bounds.max.y, Bounds.center.z + Bounds.max.z);
        go.transform.SetParent(transform, true);
        frontCenterHigh = go.transform;
        go = new GameObject("Right");
        go.transform.position = new Vector3(Bounds.center.x + Bounds.max.x, Bounds.min.y + 0.5f, Bounds.center.z + Bounds.max.z);
        go.transform.SetParent(transform, true);
        frontRight            = go.transform;
        go                    = new GameObject("Left");
        go.transform.position = new Vector3(Bounds.center.x - Bounds.max.x, Bounds.min.y + 0.5f, Bounds.center.z + Bounds.max.z);
        go.transform.SetParent(transform, true);
        frontLeft = go.transform;
    }
Пример #55
0
    bool RollNoble(OfficerRoles r)
    {
        float odds = .015f;

        switch (r)
        {
        case OfficerRoles.Navy:
            odds = .1f;
            break;

        case OfficerRoles.Army:
            odds = .03f;
            break;

        case OfficerRoles.Government:
            odds = .4f;
            break;

        case OfficerRoles.Research:
            odds = .02f;
            break;

        case OfficerRoles.Intelligence:
            odds = 0f;
            break;

        case OfficerRoles.Police:
            odds = 0f;
            break;

        case OfficerRoles.Child:
            break;

        case OfficerRoles.Corporate:
            odds = .025f;
            break;

        case OfficerRoles.Social:
            odds = .75f;
            break;

        case OfficerRoles.Merchant:
            odds = 0f;
            break;

        case OfficerRoles.Scientist:
            odds = .02f;
            break;

        case OfficerRoles.Politician:
            odds = .6f;
            break;

        case OfficerRoles.Media:
            odds = .05f;
            break;

        case OfficerRoles.Engineer:
            odds = .02f;
            break;

        case OfficerRoles.Noble:
            odds = 1f;
            break;

        case OfficerRoles.Retired:
            break;

        case OfficerRoles.Terrorist:
            odds = .01f;
            break;

        case OfficerRoles.Rebel:
            odds = .01f;
            break;

        case OfficerRoles.Spy:
            odds = .01f;
            break;

        case OfficerRoles.Criminal:
            odds = .01f;
            break;

        default:
            throw new ArgumentOutOfRangeException("r", r, null);
        }
        return(rnd.NextFloat(0, 1f) < odds);
    }
Пример #56
0
        private bool FireWeapon(
            TargetTuple target,
            Vector3 displacement,
            float distance,
            bool isServer)
        {
            Ammo ammo = PickBestAmmo(target, displacement, distance);

            if (ammo == null)
            {
                return(false);
            }

            ammo.ShellCountRemaining--;

            // sound
            _audioSource.PlayOneShot(ammo.ShotSound, _shotVolume);

            if (ammo.MuzzleFlashEffect != null)
            {
                ammo.MuzzleFlashEffect.transform.LookAt(target.Position);
                ammo.MuzzleFlashEffect.Play();
            }

            GameObject shell = GameObject.Instantiate(
                _shellPrefab,
                _barrelTip.position,
                _barrelTip.transform.rotation);

            GameObject.Instantiate(ammo.ShellArtPrefab, shell.transform);

            float   roll             = _random.NextFloat(0.0, 100.0);
            bool    isHit            = roll <= ammo.Accuracy;
            Vector3 shellDestination = target.Position;

            if (!isHit)
            {
                int deviationMode = (int)roll % 4;

                float missFactor = _random.NextFloat(
                    Constants.MISS_FACTOR_MIN,
                    Constants.MISS_FACTOR_MAX);

                float weightX = _random.NextFloat(0, 1);

                switch (deviationMode)
                {
                case 0:
                    shellDestination.x += distance * missFactor * weightX;
                    shellDestination.y += distance * missFactor * (1 - weightX);
                    break;

                case 1:
                    shellDestination.x -= distance * missFactor * weightX;
                    shellDestination.y += distance * missFactor * (1 - weightX);
                    break;

                case 2:
                    shellDestination.x += distance * missFactor * weightX;
                    shellDestination.y -= distance * missFactor * (1 - weightX);
                    break;

                case 3:
                    shellDestination.x -= distance * missFactor * weightX;
                    shellDestination.y -= distance * missFactor * (1 - weightX);
                    break;
                }
            }

            ShellBehaviour shellBehaviour = shell.GetComponent <ShellBehaviour>();

            shellBehaviour.Initialize(shellDestination, ammo);

            if (isServer)
            {
                if (target.IsUnit)
                {
                    if (isHit && !ammo.IsAoe)
                    {
                        target.Enemy.HandleHit(
                            ammo.DamageType, ammo.DamageValue, displacement, distance);
                    }
                }
                else
                {
                    // HE damage is applied by the shellBehavior when it explodes
                }
            }

            return(true);
        }
Пример #57
0
        ///// <summary>
        ///// Adds SimpleStroke copy content
        ///// </summary>
        ///// <param name="copy"></param>
        //protected override void OnCopy(Descriptor copy)
        //{
        //    base.OnCopy(copy);
        //    ISimpleStroke ss = copy as ISimpleStroke;
        //    ss.Color = Color;
        //    ss.Width = Width;
        //    ss.DashStyle = this.DashStyle;
        //}

        /// <summary>
        /// Handles randomization of simple stroke content
        /// </summary>
        /// <param name="generator">The random generator to use for randomizing characteristics.</param>
        protected override void OnRandomize(Random generator)
        {
            _color = generator.NextColor();
            Opacity = generator.NextFloat();
            _width = generator.NextFloat(10);
            _dashStyle = generator.NextEnum<DashStyle>();
            base.OnRandomize(generator);
        }
Пример #58
0
 /// <summary>
 /// Returns a random vector between the given vectors.
 /// </summary>
 static public Vector3 NextVector3(this Random inRandom, Vector3 inStart, Vector3 inEnd)
 {
     return(new Vector3(inRandom.NextFloat(inStart.x, inEnd.x), inRandom.NextFloat(inStart.y, inEnd.y), inRandom.NextFloat(inStart.z, inEnd.z)));
 }
Пример #59
0
        /// <summary>
        /// Occurs during the randomizing process
        /// </summary>
        /// <param name="generator"></param>
        protected override void OnRandomize(Random generator)
        {
            _color = generator.NextColor();
            Opacity = generator.NextFloat();
            _pointShape = generator.NextEnum<PointShape>();

            base.OnRandomize(generator);
        }
Пример #60
0
 public float SeededRandom(System.Random rand)
 {
     return(MinValue + (float)rand.NextFloat() * RangeSize);
 }