Beispiel #1
0
 public void DrawDamageModifiers(SpriteBatch spriteBatch, Camera cam, Vector2 startPos, bool isScreenSpace)
 {
     foreach (var modifier in damageModifiers)
     {
         float   rotation = -body.TransformedRotation + GetArmorSectorRotationOffset(modifier.ArmorSectorInRadians) * Dir;
         Vector2 forward  = VectorExtensions.Forward(rotation);
         float   size     = ConvertUnits.ToDisplayUnits(body.GetSize().Length() / 2);
         if (isScreenSpace)
         {
             size *= cam.Zoom;
         }
         Color color = modifier.DamageMultiplier > 1 ? Color.Red : Color.GreenYellow;
         int   width = 4;
         if (!isScreenSpace)
         {
             width = (int)Math.Round(width / cam.Zoom);
         }
         GUI.DrawLine(spriteBatch, startPos, startPos + Vector2.Normalize(forward) * size, color, width: width);
         int thickness = 2;
         if (!isScreenSpace)
         {
             thickness = (int)Math.Round(thickness / cam.Zoom);
         }
         ShapeExtensions.DrawSector(spriteBatch, startPos, size, GetArmorSectorSize(modifier.ArmorSectorInRadians) * Dir, 40, color, rotation + MathHelper.Pi, thickness);
     }
 }
        public void LoadFromData(StrokeData sData)
        {
            m_TotalLength = 0;
            Vector3 prevPos = Vector3.zero;

            for (int i = 0; i < sData.m_RawStrokeNodeData.Length; i++)
            {
                TransformData sNodeData = sData.m_RawStrokeNodeData[i];

                Vector3 pos   = VectorExtensions.Parse(sNodeData.m_PosData);
                Vector3 rot   = VectorExtensions.Parse(sNodeData.m_RotData);
                Vector3 scale = VectorExtensions.Parse(sNodeData.m_ScaleData);

                // For each stroke node data add a new node
                StrokeNode newNode = new StrokeNode(pos, Quaternion.Euler(rot), scale);
                m_RawStrokeNodes.Add(newNode);

                // Accumulate length
                if (i > 0)
                {
                    m_TotalLength += Vector3.Distance(pos, prevPos);
                }

                prevPos = pos;
            }

            // Update spaced stroke nodes
            UpdateSpacedStrokeNodes(true);

            //Vector3 colVec = VectorExtensions.Parse(sData.m_Color);
            // m_StrokeRenderer.SetColour(m_StrokeRenderer.m_Color);
        }
Beispiel #3
0
        private static void SolveBuildingInNoSoilSmallVRFStochastic()
        {
            VectorExtensions.AssignTotalAffinityCount();
            Model model = new Model();

            model.SubdomainsDictionary.Add(1, new Subdomain()
            {
                ID = 1
            });
            BeamBuildingBuilder.MakeBeamBuilding(model, 20, 20, 20, 5, 4, model.NodesDictionary.Count + 1,
                                                 model.ElementsDictionary.Count + 1, 1, 4, false, false);
            model.Loads.Add(new Load()
            {
                Amount = -100, Node = model.Nodes[21], DOF = DOFType.X
            });
            model.ConnectDataStructures();

            PowerSpectrumTargetEvaluatorCoefficientsProvider stochasticProvider = new PowerSpectrumTargetEvaluatorCoefficientsProvider(10, 0.1, 1.2, 20, 200, DOFType.X,
                                                                                                                                       0.1, 200, 1e-10);


            SolverSkyline     solver        = new SolverSkyline(model);
            ProblemStructural provider      = new ProblemStructural(model, solver.SubdomainsDictionary);
            LinearAnalyzer    analyzer      = new LinearAnalyzer(solver, solver.SubdomainsDictionary);
            StaticAnalyzer    childAnalyzer = new StaticAnalyzer(provider, analyzer, solver.SubdomainsDictionary);
            VRFMonteCarloAnalyzerWithStochasticMaterial stochasticAnalyzer = new VRFMonteCarloAnalyzerWithStochasticMaterial(model, provider, childAnalyzer, solver.SubdomainsDictionary,
                                                                                                                             stochasticProvider, stochasticProvider, 1, 20, "monteCarlo");


            analyzer.LogFactories[1] = new LinearAnalyzerLogFactory(new int[] { 420 });

            //stochasticAnalyzer.BuildMatrices();
            //childAnalyzer.Initialize();
            stochasticAnalyzer.Solve();
        }
Beispiel #4
0
        /// <summary>
        /// Convert Vector3 World Space location to Position taking account of zoom, scale and mapscale
        /// </summary>
        /// <param name="position">Vector3 World Space coordinates</param>
        /// <returns>Position</returns>
        static public IPosition ToPosition(this Vector3 position)
        {
            Vector3 mapLocal = AppState.instance.map.transform.InverseTransformPoint(position);

            Mapbox.Utils.Vector2d _latlng = VectorExtensions.GetGeoPosition(mapLocal, AppState.instance.abstractMap.CenterMercator, AppState.instance.abstractMap.WorldRelativeScale);
            return(new Position(_latlng.x, _latlng.y, mapLocal.y));
        }
Beispiel #5
0
        private NavigationPoint GetNearestPointInDirection(Vector3 direction, float maxDistance)
        {
            GameObject nearestPoint           = null;
            float      nearestDistanceSquared = float.MaxValue;
            float      maxDistanceSquared     = maxDistance * maxDistance;

            for (int i = 0; i < navigationPointsContainer.transform.childCount; i++)
            {
                GameObject point = navigationPointsContainer.transform.GetChild(i).gameObject;

                if (point != gameObject)
                {
                    Vector3 directionToPoint = point.transform.position - transform.position;
                    if (VectorExtensions.IsSameDirection(direction, directionToPoint, anglePrecision))
                    {
                        float distanceSquared = directionToPoint.sqrMagnitude;
                        if (distanceSquared <= maxDistanceSquared && distanceSquared < nearestDistanceSquared)
                        {
                            nearestPoint           = point;
                            nearestDistanceSquared = distanceSquared;
                        }
                    }
                }
            }

            return(nearestPoint == null ? null : nearestPoint.GetComponent <NavigationPoint>());
        }
Beispiel #6
0
 private void TryAngleSingle(OnHitDetectData data)
 {
     if (Vector2.Angle(data.BulletShootDirection, VectorExtensions.DegreeToVector2(rotation - 90)) <= 55)
     {
         ShootAtDirection(rotation + 90, data);
     }
 }
        public void LimitTest(double inputX, double inputY, double limit, double expectedX, double expectedY)
        {
            var input    = new Vector2((float)inputX, (float)inputY);
            var expected = new Vector2((float)expectedX, (float)expectedY);

            Assert.AreEqual(expected, VectorExtensions.Limit(input, (float)limit));
        }
        [DataRow(0, -2, -1f / 2f * MathF.PI, 2)] // 270°
        public void ToPolarTest(double inputX, double inputY, double expectedX, double expectedY)
        {
            var input    = new Vector2((float)inputX, (float)inputY);
            var expected = new Vector2((float)expectedX, (float)expectedY);

            Assert.AreEqual(expected, VectorExtensions.ToPolar(input));
        }
Beispiel #9
0
    public void gardenDecorBuildConfirmed()
    {
        string longLat = VectorExtensions.GetGeoPosition(
            tweakedGardenDecor.transform.position,
            Map.GetComponent <BasicMap>().CenterMercator,
            Map.GetComponent <BasicMap>().WorldRelativeScale
            ).ToString();

        BaseGardenDecor newDecor = new BaseGardenDecor(gardenDecorToBuild.gardenDecorType, longLat, 0);

        newDecor.yRotation = tweakedGardenDecor.transform.rotation.eulerAngles.y;
        newDecor.scale     = tweakedGardenDecor.transform.localScale.x;
        newDecor.variation = tweakedGardenDecor.GetComponent <GardenDecorWorld>().representedDecor.variation;
        newDecor.yOffset   = tweakedGardenDecor.transform.localPosition.y - 0.2f;
        PetKeeper.pet.Base.baseGardenDecors.Add(newDecor);

        tweakedGardenDecor.GetComponent <GardenDecorWorld>().init(newDecor);

        PetKeeper.pet.buildingMaterials -= gardenDecorToBuild.bmCost;
        PetKeeper.pet.inventory.gardenDecorCounts[(int)gardenDecorToBuild.gardenDecorType] -= 1;

        queueRewardText("Built Decor!", new Color(0.7f, 0.7f, 0.7f, 1));

        isTweakingGardenDecor = false;

        PetKeeper.pet.Save(false);

        exitModePressed();
    }
Beispiel #10
0
        /// <summary>
        /// given the relative velocity between the two objects and the MTV this method modifies the relativeVelocity to make it a collision
        /// response.
        /// </summary>
        /// <param name="relativeVelocity">Relative velocity.</param>
        /// <param name="minimumTranslationVector">Minimum translation vector.</param>
        void calculateResponseVelocity(ref Vector2 relativeVelocity, ref Vector2 minimumTranslationVector, out Vector2 responseVelocity)
        {
            // first, we get the normalized MTV in the opposite direction: the surface normal
            var     inverseMTV = minimumTranslationVector * -1f;
            Vector2 normal;

            VectorExtensions.Normalize(ref inverseMTV, out normal);

            // the velocity is decomposed along the normal of the collision and the plane of collision.
            // The elasticity will affect the response along the normal (normalVelocityComponent) and the friction will affect
            // the tangential component of the velocity (tangentialVelocityComponent)
            float n;

            VectorExtensions.Dot(ref relativeVelocity, ref normal, out n);

            var normalVelocityComponent     = normal * n;
            var tangentialVelocityComponent = relativeVelocity - normalVelocityComponent;

            if (n > 0.0f)
            {
                normalVelocityComponent = Vector2.zero;
            }

            // if the squared magnitude of the tangential component is less than glue then we bump up the friction to the max
            var coefficientOfFriction = _friction;

            if (tangentialVelocityComponent.LengthSquared() < _glue)
            {
                coefficientOfFriction = 1.01f;
            }

            // elasticity affects the normal component of the velocity and friction affects the tangential component
            responseVelocity = -(1.0f + _elasticity) * normalVelocityComponent - coefficientOfFriction * tangentialVelocityComponent;
        }
Beispiel #11
0
        private static void SolveBuildingInNoSoilSmall()
        {
            VectorExtensions.AssignTotalAffinityCount();
            Model model = new Model();

            model.SubdomainsDictionary.Add(1, new Subdomain()
            {
                ID = 1
            });
            BeamBuildingBuilder.MakeBeamBuilding(model, 20, 20, 20, 5, 4, model.NodesDictionary.Count + 1,
                                                 model.ElementsDictionary.Count + 1, 1, 4, false, false);
            model.Loads.Add(new Load()
            {
                Amount = -100, Node = model.Nodes[21], DOF = DOFType.X
            });
            model.ConnectDataStructures();

            SolverSkyline     solver         = new SolverSkyline(model);
            ProblemStructural provider       = new ProblemStructural(model, solver.SubdomainsDictionary);
            LinearAnalyzer    analyzer       = new LinearAnalyzer(solver, solver.SubdomainsDictionary);
            StaticAnalyzer    parentAnalyzer = new StaticAnalyzer(provider, analyzer, solver.SubdomainsDictionary);

            analyzer.LogFactories[1] = new LinearAnalyzerLogFactory(new int[] { 420 });

            parentAnalyzer.BuildMatrices();
            parentAnalyzer.Initialize();
            parentAnalyzer.Solve();
        }
Beispiel #12
0
        private void OperateRepairTool(float deltaTime)
        {
            character.CursorPosition = Item.WorldPosition;
            if (character.Submarine != null)
            {
                character.CursorPosition -= character.Submarine.Position;
            }
            if (repairTool.Item.RequireAimToUse)
            {
                character.SetInput(InputType.Aim, false, true);
            }
            Vector2 fromToolToTarget = Item.Position - repairTool.Item.Position;

            if (fromToolToTarget.LengthSquared() < MathUtils.Pow(repairTool.Range / 2, 2))
            {
                // Too close -> steer away
                character.AIController.SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(character.SimPosition - Item.SimPosition) / 2);
            }
            else
            {
                character.AIController.SteeringManager.Reset();
            }
            if (VectorExtensions.Angle(VectorExtensions.Forward(repairTool.Item.body.TransformedRotation), fromToolToTarget) < MathHelper.PiOver4)
            {
                repairTool.Use(deltaTime, character);
            }
        }
        public virtual IEnumerator LoadRoutine()
        {
            yield return(new WaitForEndOfFrame());

            possibleMoves = new Vector2[6];
            int i = 0;

            for (float angle = 0; angle < 360; angle += 360f / 6)
            {
                possibleMoves[i] = VectorExtensions.FromFacingAngle(angle) * WORLD_SCALE;
                i++;
            }
            GetSingleton <SaveAndLoadManager>().Setup();
            if (!HasPlayedBefore)
            {
                GetSingleton <SaveAndLoadManager>().DeleteAll();
                HasPlayedBefore = true;
                GetSingleton <SaveAndLoadManager>().OnLoaded();
            }
            else
            {
                GetSingleton <SaveAndLoadManager>().LoadMostRecent();
            }
            // GetSingleton<AdsManager>().ShowAd ();
            Init();
            yield break;
        }
Beispiel #14
0
        ///
        public override float ComputeObjective()
        {
            double user_complexity = 0;

            for (int user_id = 0; user_id <= MaxUserID; user_id++)
            {
                if (ratings.CountByUser.Count > user_id)
                {
                    user_complexity += Math.Pow(VectorExtensions.EuclideanNorm(user_factors.GetRow(user_id)), 2);
                    user_complexity += BiasReg * Math.Pow(user_bias[user_id], 2);
                }
            }
            double item_complexity = 0;

            for (int item_id = 0; item_id <= MaxItemID; item_id++)
            {
                if (ratings.CountByItem.Count > item_id)
                {
                    item_complexity += Math.Pow(VectorExtensions.EuclideanNorm(item_factors.GetRow(item_id)), 2);
                    item_complexity += BiasReg * Math.Pow(item_bias[item_id], 2);
                }
            }
            double complexity = RegU * user_complexity + RegI * item_complexity;

            double social_regularization = 0;

            for (int user_id = 0; user_id <= MaxUserID; user_id++)
            {
                double bias_diff    = 0;
                var    factor_diffs = new double[NumFactors];
                foreach (int v in user_connections[user_id])
                {
                    bias_diff -= user_bias[v];
                    for (int f = 0; f < factor_diffs.Length; f++)
                    {
                        factor_diffs[f] -= user_factors[v, f];
                    }
                }

                if (user_connections[user_id].Count > 0)
                {
                    bias_diff /= user_connections[user_id].Count;
                }
                bias_diff             += user_bias[user_id];
                social_regularization += Math.Pow(bias_diff, 2);

                for (int f = 0; f < factor_diffs.Length; f++)
                {
                    if (user_connections[user_id].Count > 0)
                    {
                        factor_diffs[f] /= user_connections[user_id].Count;
                    }
                    factor_diffs[f]       += user_factors[user_id, f];
                    social_regularization += Math.Pow(factor_diffs[f], 2);
                }
            }
            social_regularization *= this.social_regularization;

            return((float)(ComputeLoss() + complexity + social_regularization));
        }
    /// <summary>
    /// Invoked when players collider intersects with checkpoint collider
    /// </summary>
    /// <param name="other"></param>
    protected void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player" && other.name == "Player")
        {
            Player     player = other.gameObject.GetComponent <Player>();
            PlayerData data   = new PlayerData();

            if (changeScene)
            {
                // if checkpoint changes scene, save values for the new scene
                data.playerPosition = VectorExtensions.Vector3ToString(new Vector3(0, 0, 0));
            }
            else
            {
                data.playerPosition = VectorExtensions.Vector3ToString(other.gameObject.transform.position);
            }

            data.playerRotation = VectorExtensions.Vector3ToString(other.gameObject.transform.localEulerAngles);
            data.playerScale    = VectorExtensions.Vector3ToString(other.gameObject.transform.localScale);
            data.playerEnergy   = other.gameObject.GetComponent <Player>().LightEnergy.CurrentEnergy;
            DataManager.SaveFile(data);

            if (changeScene)
            {
                StartCoroutine(ChangeLevel());
            }
        }
    }
        private void StartDash()
        {
            if (stamina <= 0.0 || playerEntity.State == PlayerState.Dizzy)
            {
                return;
            }
            playerEntity.SwitchToState(PlayerState.Dashing);
            dashTime = 0;

            Entity.GetComponent <AudioSourceComponent>().PlaySound("Audio/dashSwoosh");

            var physicsComponent = playerEntity.GetComponent <PhysicsComponent>();

            physicsComponent.ReplaceShape(new CircleShape(0.5f, 1.0f));
            physicsComponent.Fixture.IsSensor            = true;
            physicsComponent.Fixture.CollisionCategories = GameConstants.CollisionCategorySensor;
            physicsComponent.Fixture.CollidesWith        = Category.All & ~GameConstants.CollisionCategorySensor;
            physicsComponent.Fixture.OnCollision        += OnCollision;

            stamina -= dashStaminaCost;

            if (Entity.Body.LinearVelocity.LengthSquared() > 0.0000001f)
            {
                dashDirection = Vector2.Normalize(Entity.Body.LinearVelocity);
            }
            else
            {
                dashDirection = VectorExtensions.AngleToUnitVector(Entity.Body.Rotation);
            }
        }
Beispiel #17
0
        private void PlaceLights(Scene destination)
        {
            for (var i = 0; i < 9; i++)
            {
                var position = VectorExtensions.Random(3, 12);
                var color    = VectorExtensions.RandomColor(200);

                var item  = new Light();
                var model = new RenderModelComponent(item, ModelFactory.HalfTriangularThing(color));

                var xform = new TransformComponent(item, position);

                var light = new PointLightEmitterComponent(item)
                {
                    Light = new PointLight()
                    {
                        Color    = new Vector3(color.X, color.Y, color.Z),
                        Position = Vector3.Zero,
                        Radius   = 20f
                    }
                };

                item.SetComponents(new Component[] {
                    model,
                    xform,
                    light
                });

                destination.Entities.Add(Guid.NewGuid(), item);
            }
        }
        public void Update(float elapsedSeconds, float totalSeconds)
        {
            Vector2 newDirection = barnPosition - Entity.Body.Position;

            newDirection.Normalize();
            float desiredRotation = newDirection.UnitVectorToAngle();
            float actualRotation  = Entity.Body.Rotation;

            float angleDistance = desiredRotation - actualRotation;

            angleDistance = MathHelper.WrapAngle(angleDistance);

            if (angleDistance > 0)
            {
                Entity.Body.AngularVelocity = Math.Min(angleDistance / elapsedSeconds, 6);
            }
            else if (angleDistance < 0)
            {
                Entity.Body.AngularVelocity = Math.Max(angleDistance / elapsedSeconds, -6);
            }
            else
            {
                Entity.Body.AngularVelocity = 0;
            }

            if ((barnPosition - Entity.Body.Position).LengthSquared() < 0.5 * 0.5)
            {
                this.Entity.Die();
            }

            Entity.Body.LinearVelocity = VectorExtensions.AngleToUnitVector(Entity.Body.Rotation);
        }
Beispiel #19
0
 public virtual void OnEnable()
 {
     if (Random.Range(0, 2) == 1)
     {
         trs.localScale = VectorExtensions.Multiply(trs.localScale, new Vector3(-1, 1, 1));
     }
 }
Beispiel #20
0
        public override void Update(float elapsedSeconds)
        {
            foreach (Entity e in this.actives.Values)
            {
                TransformComponent transform = e.GetComponent <TransformComponent>();
                MotionComponent    motion    = e.GetComponent <MotionComponent>();
                TargetComponent    target    = e.GetComponent <TargetComponent>();

                System.Diagnostics.Debug.Assert(transform != null, "PositionComponent not found");
                System.Diagnostics.Debug.Assert(motion != null, "VelocityComponent not found");
                System.Diagnostics.Debug.Assert(target != null, "TargetComponent not found");

                if (EntityWorld.EntityManager.IsAlive(target.TargetId))
                {
                    TransformComponent targetTransform = this.EntityWorld.ComponentManager.GetComponent <TransformComponent>(target.TargetId);

                    if (targetTransform != null)
                    {
                        Vector2 delta = targetTransform.Position - transform.Position;
                        float   destinationDirection = VectorExtensions.Vector2ToAngle(delta);
                        int     accelFactor          = 10;
                        float   newRotation          = MathExtensions.LerpAngle(MathHelper.WrapAngle(transform.Rotation), MathHelper.WrapAngle(destinationDirection), /*0.1f*/ 2 * elapsedSeconds);
                        transform.Rotation = newRotation;
                        motion.AddAcceleration(VectorExtensions.AngleToVector2(transform.Rotation) * GameConfig.Projectile.Velocity * accelFactor);
                        //motion.AddAngularAcceleration((destinationDirection - transform.Rotation) * 0.5f);
                    }
                }
                //else
                //{
                //    //target lost
                //    motion.AddAcceleration(VectorExtensions.AngleToVector2(transform.Rotation) * GameConfig.Projectile.Velocity * accelFactor);
                //}
            }
        }
Beispiel #21
0
        public override void OnUpdate(float elapsedSeconds)
        {
            base.OnUpdate(elapsedSeconds);

            if (!this.poweringUp)
            {
                if (Kadro.Input.KeyboardInput.IsKeyDown(Keys.Left))
                {
                    this.Transform.Rotation -= this.resolutionsPerSecond * elapsedSeconds;
                    this.Transform.Position  = VectorExtensions.Rotate(this.Transform.Position, -this.resolutionsPerSecond * elapsedSeconds, focusPosition - offset);
                }

                if (Kadro.Input.KeyboardInput.IsKeyDown(Keys.Right))
                {
                    this.Transform.Rotation += this.resolutionsPerSecond * elapsedSeconds;
                    this.Transform.Position  = VectorExtensions.Rotate(this.Transform.Position, this.resolutionsPerSecond * elapsedSeconds, focusPosition - offset);
                }

                if (MouseInput.OnMouseMoved())
                {
                    float targetAngle = (GameScene.ActiveScene.ViewToWorld(MouseInput.PositionVector) - focusPosition + offset).PerpRight().ToPolar();
                    //targetAngle = MathExtensions.LerpAngle(this.Transform.Rotation, targetAngle, 1.0f * elapsedSeconds);
                    this.Transform.Rotation = targetAngle;
                    this.Transform.Position = VectorExtensions.Rotate(focusPosition, targetAngle, focusPosition - offset);
                }

                if (Kadro.Input.KeyboardInput.OnKeyDown(Keys.Space))
                {
                    this.poweringUp = true;

                    // add constant velocity to move back
                    RigidBody r = this.Components.Get <RigidBodyComponent>().RigidBody;
                    r.AddVelocityChange(VectorExtensions.AngleToVector2(this.Transform.Rotation).PerpLeft() * this.poweringUpVelocity * elapsedSeconds);
                }
            }

            if (this.poweringUp && Kadro.Input.KeyboardInput.IsKeyDown(Keys.Space))
            {
                this.timeSinceStart += elapsedSeconds;
            }

            if ((this.poweringUp && Kadro.Input.KeyboardInput.OnKeyUp(Keys.Space)) || this.timeSinceStart > this.releaseTime)
            {
                // release
                this.timeSinceStart = 0f;
                this.releasing      = true;
                RigidBody r = this.Components.Get <RigidBodyComponent>().RigidBody;
                r.Velocity        = Vector2.Zero;
                r.AngularVelocity = 0;
            }

            if (this.releasing)
            {
                // accelerate cue until it hits the ball
                RigidBody r = this.Components.Get <RigidBodyComponent>().RigidBody;
                r.AddForce(-VectorExtensions.AngleToVector2(this.Transform.Rotation).PerpLeft() * this.releaseForce * elapsedSeconds);
            }
        }
Beispiel #22
0
 public virtual void AddAsteroid(Entity e, Vector2 position, float rotation, Vector2 scale)
 {
     e.AddComponent(new TransformComponent(position, rotation, scale));
     e.AddComponent(new MotionComponent(VectorExtensions.AngleToVector2(rotation) * GameConfig.Asteroid.Velocity, ((rotation % 2 * Math.PI) - Math.PI) < 0 ? -GameConfig.Asteroid.AngularVelocity : +GameConfig.Asteroid.AngularVelocity, GameConfig.Asteroid.Velocity, GameConfig.Asteroid.AngularVelocity));
     e.AddComponent(new CollidableComponent(this.LayerManager.GetBit(GameConfig.Asteroid.CollisionLayer),
                                            this.LayerManager.GetBit(GameConfig.Spaceship.CollisionLayer) | this.LayerManager.GetBit(GameConfig.Projectile.CollisionLayer),
                                            new CircleCollider(GameConfig.Asteroid.Large * scale.X / 2f), e.EntityId));
     e.AddComponent(new TagComponent(GameConfig.Asteroid.Tag));
 }
Beispiel #23
0
 public virtual void Do()
 {
     points = new Vector2[pointCount];
     for (int i = 0; i < pointCount; i++)
     {
         points[i] = circle.center + VectorExtensions.FromFacingAngle((i * 360f / pointCount) * (1f / 360f) * 360) * circle.radius;
     }
     polygonCollider.points = points;
 }
Beispiel #24
0
        public static Vector3 GetBlinkPosition(this Unit unit, Vector3 direction, float remainingTime)
        {
            var angle = (float)(Math.Max(remainingTime, 0) * unit.GetTurnRate() / 0.03);

            var left  = VectorExtensions.FromPolarCoordinates(1, unit.NetworkRotationRad + angle).ToVector3();
            var right = VectorExtensions.FromPolarCoordinates(1, unit.NetworkRotationRad - angle).ToVector3();

            return(unit.Position + (left.Distance2D(direction) < right.Distance2D(direction) ? left : right) * 100);
        }
Beispiel #25
0
        /// <summary>
        ///     The get stack damage.
        /// </summary>
        /// <param name="hero">
        ///     The hero.
        /// </param>
        /// <param name="inFrontDistance">
        ///     The in front distance.
        /// </param>
        /// <returns>
        ///     The <see cref="Tuple" />.
        /// </returns>
        public static Tuple <float, IEnumerable <RemoteMine> > GetStackDamage(this Unit hero, float inFrontDistance = 0)
        {
            var detonatableMines = new List <RemoteMine>();

            if (Variables.Stacks == null || !Variables.Stacks.Any())
            {
                return(new Tuple <float, IEnumerable <RemoteMine> >(0, detonatableMines));
            }

            var rotSpeed = Prediction.RotSpeedDictionary.ContainsKey(hero.Handle)
                               ? Prediction.RotSpeedDictionary[hero.Handle]
                               : 0;
            var heroPosition = inFrontDistance > 0
                                   ? hero.Position
                               + VectorExtensions.FromPolarCoordinates(
                1f,
                (float)(hero.NetworkRotationRad + rotSpeed)).ToVector3() * inFrontDistance
                                   : hero.Position;

            if (hero.NetworkActivity == NetworkActivity.Move)
            {
                heroPosition +=
                    VectorExtensions.FromPolarCoordinates(1f, (float)(hero.NetworkRotationRad + rotSpeed)).ToVector3()
                    * (float)(Variables.Techies.GetTurnTime(hero) + Game.Ping / 1000) * hero.MovementSpeed;
            }

            var tempDamage   = 0f;
            var nearestStack = Variables.Stacks.MinOrDefault(x => x.Position.Distance(heroPosition));

            if (nearestStack == null || nearestStack.Position.Distance(heroPosition) > 1000)
            {
                return(new Tuple <float, IEnumerable <RemoteMine> >(0, detonatableMines));
            }

            foreach (var landMine in nearestStack.LandMines.Where(x => x.Distance(heroPosition) <= x.Radius))
            {
                if (tempDamage >= hero.Health)
                {
                    return(new Tuple <float, IEnumerable <RemoteMine> >(tempDamage, detonatableMines));
                }

                tempDamage += Variables.Damage.GetLandMineDamage(landMine.Level, hero.ClassID);
            }

            foreach (var remoteMine in nearestStack.RemoteMines.Where(x => x.Distance(heroPosition) <= x.Radius))
            {
                if (tempDamage >= hero.Health)
                {
                    break;
                }

                detonatableMines.Add(remoteMine);
                tempDamage += Variables.Damage.GetRemoteMineDamage(remoteMine.Level, hero.ClassID, hero);
            }

            return(new Tuple <float, IEnumerable <RemoteMine> >(tempDamage, detonatableMines));
        }
Beispiel #26
0
 public override void Attached()
 {
     if (!entity.IsOwner)
     {
         return;
     }
     selfRotationSpeed = Random.Range(0.0f, selfRotationSpeed);
     selfRotationAxis  = VectorExtensions.RandomAxis();
     orbitCenter       = GameObjectManager.Instance.Sun.transform;
 }
        private void Move(float elapsedSeconds, float desiredSpeed)
        {
            Vector2 desiredVelocity = VectorExtensions.AngleToUnitVector(Entity.Body.Rotation);

            desiredVelocity *= desiredSpeed;

            float drag = 0.1f;

            Entity.Body.LinearVelocity = drag * desiredVelocity + (1.0f - drag) * Entity.Body.LinearVelocity;
        }
Beispiel #28
0
    void Awake()
    {
        HalfDuration = Duration / 2f;

        MaxScaleVector = VectorExtensions.FromValue(MaxScale);
        DefaultScale   = transform.localScale;

        UpEaser   = Ease.FromType(UpEase);
        DownEaser = Ease.FromType(DownEase);
    }
        /// <summary>
        ///     The get nearest stack to kill.
        /// </summary>
        /// <param name="hero">
        ///     The hero.
        /// </param>
        /// <param name="predict">
        ///     The predict.
        /// </param>
        /// <returns>
        ///     The <see cref="Stack" />.
        /// </returns>
        private static Stack GetNearestStackToPush(Unit hero, Vector3 predict)
        {
            var detonatableMines = new List <RemoteMine>();

            if (Variables.Stacks == null || !Variables.Stacks.Any())
            {
                return(null);
            }

            var heroPosition = predict;

            var tempDamage   = 0f;
            var nearestStack =
                Variables.Stacks.Where(
                    x =>
                    VectorExtensions.Distance(x.Position, heroPosition) <= PushRange + 400 &&
                    VectorExtensions.Distance(x.Position, heroPosition) > PushRange - 400)
                .MinOrDefault(x => VectorExtensions.Distance(x.Position, heroPosition));

            if (nearestStack == null)
            {
                return(null);
            }

            foreach (var landMine in
                     nearestStack.LandMines.Where(
                         x =>
                         x.Distance(heroPosition) <= x.Radius + PushRange &&
                         x.Distance(hero.Position) <= x.Radius + PushRange))
            {
                if (tempDamage >= hero.Health)
                {
                    return(nearestStack);
                }

                tempDamage += Variables.Damage.GetLandMineDamage(landMine.Level, hero.Handle);
            }

            foreach (var remoteMine in
                     nearestStack.RemoteMines.Where(
                         x =>
                         x.Distance(heroPosition) <= x.Radius + PushRange &&
                         x.Distance(hero.Position) <= x.Radius + PushRange))
            {
                if (tempDamage >= hero.Health)
                {
                    return(nearestStack);
                }

                detonatableMines.Add(remoteMine);
                tempDamage += Variables.Damage.GetRemoteMineDamage(remoteMine.Level, hero.Handle, hero);
            }

            return(!(tempDamage >= hero.Health) ? null : nearestStack);
        }
Beispiel #30
0
        /// <summary>
        /// Updates the transform and state of this object every frame, depending on
        /// manipulations and docking state.
        /// </summary>
        public void Update()
        {
            if (isDragging && overlappingPositions.Count > 0)
            {
                var closestPosition = GetClosestPosition();
                if (closestPosition.IsOccupied)
                {
                    closestPosition.GetComponentInParent <Dock>().TryMoveToFreeSpace(closestPosition);
                }
            }

            if (dockingState == DockingState.Docked || dockingState == DockingState.Docking)
            {
                Assert.IsNotNull(dockedPosition, "When a dockable is docked, its dockedPosition must be valid.");
                Assert.AreEqual(dockedPosition.DockedObject, this, "When a dockable is docked, its dockedPosition reference the dockable.");

                var lerpTime = dockingState == DockingState.Docked ? moveLerpTimeWhenDocked : moveLerpTime;

                if (!isDragging)
                {
                    // Don't override dragging
                    transform.position = Solver.SmoothTo(transform.position, dockedPosition.transform.position, Time.deltaTime, lerpTime);
                    transform.rotation = Solver.SmoothTo(transform.rotation, dockedPosition.transform.rotation, Time.deltaTime, lerpTime);
                }

                transform.localScale = Solver.SmoothTo(transform.localScale, dockedPositionScale, Time.deltaTime, lerpTime);

                if (VectorExtensions.CloseEnough(dockedPosition.transform.position, transform.position, distanceTolerance) &&
                    QuaternionExtensions.AlignedEnough(dockedPosition.transform.rotation, transform.rotation, angleTolerance) &&
                    AboutTheSameSize(dockedPositionScale.x, transform.localScale.x))
                {
                    // Finished docking
                    dockingState = DockingState.Docked;

                    // Snap to position
                    transform.position   = dockedPosition.transform.position;
                    transform.rotation   = dockedPosition.transform.rotation;
                    transform.localScale = dockedPositionScale;
                }
            }
            else if (dockedPosition == null && dockingState == DockingState.Undocking)
            {
                transform.localScale = Solver.SmoothTo(transform.localScale, originalScale, Time.deltaTime, moveLerpTime);

                if (AboutTheSameSize(originalScale.x, transform.localScale.x))
                {
                    // Finished undocking
                    dockingState = DockingState.Undocked;

                    // Snap to size
                    transform.localScale = originalScale;
                }
            }
        }