Example #1
0
    public static Node2D LeaderToFollow;                   // to save the leader node to follow

    /// <summary>
    /// Calculate a velocity to move a character towards a destination (Follow)
    /// </summary>
    /// <param name="pVelocity">the actual velocity of the character</param>
    /// <param name="pPosition">the actual global position of the character</param>
    /// <param name="pTargetPosition">the destination of the character</param>
    /// <param name="pMaxSpeed">the maximum speed the character can reach</param>
    /// <param name="pSlowRadius">(0.0f = no slow down) the circle radius around the target where the character starts to slow down</param>
    /// <param name="pMass">to slow down the character</param>
    /// <param name="pStopRadius">the circle radius around the target where the character stops</param>
    /// <returns>A vector2 to represent the destination velocity or a Vector2(0,0) if character is close to the target</returns>
    public static Vector2 Steering_Seek(Vector2 pVelocity, Vector2 pPosition, Vector2 pTargetPosition,
                                        float pMaxSpeed = STEERING_DEFAULT_MAXSPEED, float pSlowRadius = 0.0f, float pMass = STEERING_DEFAULT_MASS, float pStopRadius = STEERING_CLOSE_DISTANCE)
    {
        // Check if we have enough distance between the character and the target
        if (pPosition.DistanceTo(pTargetPosition) <= pStopRadius)
        {
            return(VECTOR_0);
        }

        // STEP 1 : use the formula to get the shortest path possible to the target
        Vector2 desire_velocity = (pTargetPosition - pPosition).Normalized() * pMaxSpeed;

        // STEP 2 : slow down the character when he is closed to the target
        if (pSlowRadius != 0.0f)
        {
            float to_target = pPosition.DistanceTo(pTargetPosition);

            // Reduce velocity if in the slow circle around the target
            if (to_target <= pSlowRadius)
            {
                desire_velocity *= ((to_target / pSlowRadius) * 0.8f) + 0.2f;       // 0.8f + 0.2f : used to not slow down too much the character
            }
        }

        // STEP 3 : apply the steering formula (use mass to slow down character's movement)
        return(_CalculateSteering(desire_velocity, pVelocity, pMass));
    }
Example #2
0
    public void FilterByMiddleHeight()
    {
        List <TimedPathNode> nodesToRomove = new List <TimedPathNode>();

        for (int i = 1; i < Nodes.Count - 1; i += 1)
        {
            Vector2 A = Nodes[i - 1].Position;
            Vector2 B = Nodes[i + 1].Position;
            Vector2 M = Nodes[i].Position;

            double ab = A.DistanceTo(B);
            double mb = M.DistanceTo(B);
            double ma = M.DistanceTo(A);

            double p = (ab + ma + mb) / 2;
            double a = System.Math.Sqrt(p * (p - ab) * (p - ma) * (p - mb));
            double h = (ab > 0) ?  2 * a / ab : 0;

            if (h > MAX_MIDDLE_HEIGHT)
            {
                nodesToRomove.Add(Nodes[i]);
            }
        }

        foreach (TimedPathNode node in nodesToRomove)
        {
            Nodes.Remove(node);
        }
    }
Example #3
0
        /// <summary>
        /// Gets the square of the area of the triangle defined by three points. This is useful when simply comparing two areas when you don't need to know exactly what the area is.
        /// </summary>
        /// <param name="vertex1">First vertex of triangle.</param>
        /// <param name="vertex2">Second vertex of triangle.</param>
        /// <param name="vertex3">Third vertex of triangle.</param>
        /// <returns>Square of the area of the triangle defined by these three vertices.</returns>
        public static float TriangleAreaSquared(Vector2 vertex1, Vector2 vertex2, Vector2 vertex3)
        {
            float side1         = vertex1.DistanceTo(vertex2);
            float side2         = vertex1.DistanceTo(vertex3);
            float side3         = vertex2.DistanceTo(vertex3);
            float semiPerimeter = (side1 + side2 + side3) / 2f;

            return(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (semiPerimeter - side3));
        }
Example #4
0
        public override void _Process(float delta)
        {
            if (!hourglasstoken.exists && RainSources.random.Next(0, 150) == 1)
            {
                hourglasstoken hourglass = (hourglasstoken)hourglasstoken.hourglassScene.Instance();
                hourglass.Position = new Vector2(RainSources.random.Next(100, 1500), RainSources.random.Next(100, 800));
                Global.stage.FindNode("HourGlass").AddChild(hourglass);
                hourglasstoken.exists  = true;
                hourglasstoken.thisone = hourglass;
            }

            if (Global.Paused)
            {
                if (Input.IsActionJustPressed("ui_accept"))
                {
                    Global.Unpause();
                }
            }
            else if (live && !Global.Paused)
            {
                liveTime += delta;
                ((Label)GetNode(new NodePath("/root/Stage/GUI/Label"))).Text = liveTime.ToString();

                Vector2 lastPosition = GetPosition();
                Vector2 newPosition  = new Vector2(positionBuffer);

                bool moved = lastPosition.DistanceTo(newPosition) > 3;
                if (moved)
                {
                    float newDirection = lastPosition.AngleToPoint(newPosition);
                    newDirection = Mathf.Min((newDirection + 0.05F) * 0.9F, newDirection); //Play with this, possible average over 3 frames or something

                    SetPosition(newPosition);
                    SetRotation(-newDirection);
                }

                boots.ForEach(b => b.Move(lastPosition.DistanceTo(newPosition), moved));
            }

            if (ITSY_AREA.GetOverlappingAreas().Contains(hourglasstoken.thisone))
            {
                Damage(-1);
                hourglasstoken.thisone.QueueFree();
                hourglasstoken.exists = false;
                invincibility         = 2;
            }
            else
            {
                invincibility -= delta;
                invincibility  = Mathf.Max(invincibility, 0);
            }
        }
        private static float PointSegment(Vector2 point, Vector2 segmentA, Vector2 segmentB, Vector2 segmentDirection, float segmentLength)
        {
            float pointProjection = segmentDirection.Dot(point - segmentA);

            if (pointProjection < -Geometry.Epsilon)
            {
                return(point.DistanceTo(segmentA));
            }
            if (pointProjection > segmentLength + Geometry.Epsilon)
            {
                return(point.DistanceTo(segmentB));
            }
            return(point.DistanceTo(segmentA + segmentDirection * pointProjection));
        }
    Vector2 avoid(List <Obstacle> obstacles)
    {
        Vector2  viewAhead      = Position + velocity.Normalized() * seeAheadDistance;
        Vector2  viewAhead2     = viewAhead * 0.5f;
        Vector2  avoidanceForce = new Vector2(0, 0);
        Obstacle closest        = null;

        foreach (Obstacle o in obstacles)
        {
            if (viewAhead.DistanceTo(o.Position) <= o.radius || viewAhead2.DistanceTo(o.Position) <= o.radius)
            {
                if (closest == null)
                {
                    closest = o;
                }
                else if (Position.DistanceTo(o.Position) < Position.DistanceTo(closest.Position))
                {
                    closest = o;
                }
            }
        }
        if (closest != null)
        {
            avoidanceForce  = viewAhead - closest.Position;
            avoidanceForce  = avoidanceForce.Normalized();
            avoidanceForce *= maxAvoidForce;
        }
        return(avoidanceForce);
    }
Example #7
0
 public static float Distance(Vector2 a, Vector2 b)
 {
     /*
      * return (Mathf.Pow(a.x-b.x,2)+Mathf.Pow(a.y-b.y,2));
      */
     return(a.DistanceTo(b));
 }
Example #8
0
        /// <summary>
        /// Adds a single household visit to the outlet nearest to the given Vector2 position.
        /// </summary>
        public void AddVisitToNearestOutlet(Vector2 position, ref List <Tuple <Vector2, Vector2> > visits)
        {
            //Any outlets to visit?
            if (outlets.Count == 0)
            {
                return;
            }

            //Loop over outlets and get distances.
            Outlet nearest         = null;
            double nearestDistance = double.MaxValue;

            foreach (var outlet in outlets)
            {
                //Found a better distance?
                double thisDist = position.DistanceTo(outlet.Position);
                if (thisDist < nearestDistance)
                {
                    nearest         = outlet;
                    nearestDistance = thisDist;
                }
            }

            //Was an outlet found? If so, add it, and log the visit to the list.
            if (nearest == null)
            {
                return;
            }
            nearest.Visit(position);
            visits.Add(new Tuple <Vector2, Vector2>(position, nearest.Position));
        }
Example #9
0
    public override void _PhysicsProcess(float delta)
    {
        cursor.Position = GetViewport().GetMousePosition();
        moveDirection   = new Vector2(
            new Vector2(OS.GetScreenSize().x / 2, OS.GetScreenSize().y / 2) - GetViewport().GetMousePosition()
            );

        moveDirection *= speed;

        var headNextPosition = new Vector2(head.Translation.x, head.Translation.y) + moveDirection;

        if (headNextPosition.DistanceTo(new Vector2(0, 0)) < 0.9)
        {
            head.Translation += new Vector3(moveDirection.x,
                                            moveDirection.y,
                                            0);
        }
        if (health < 0)
        {
            GetTree().ReloadCurrentScene();
        }

        material.AlbedoColor = MusicToRGB();
        time           += delta;
        healthBar.Value = health;
        if (Input.IsActionJustPressed("ui_cancel"))
        {
            GetTree().Quit();
        }
    }
Example #10
0
    public override void _Process(float delta)
    {
        if (!Freeze.Frozen){
            if (startTimer > 0){
                startTimer -= delta;
            } else {
                if (moveSpeed > 0){
                    var moveTarget = new Vector2(moveDistanceX, moveDistanceY) + startPosition;
                    var moveDistance = moveTarget.DistanceTo(startPosition);
                    var movePeriod = moveDistance / moveSpeed;
                    
                    if (!comebackPhase){
                        timer += (Slowable.Slow ? delta * Slowable.SpeedSlow : delta);
                        if (timer >= movePeriod){
                            timer = movePeriod;
                            comebackPhase = true;
                        }
                    } else {
                        timer -= (Slowable.Slow ? delta * Slowable.SpeedSlow : delta);
                        if (timer <= 0){
                            timer = 0;
                            comebackPhase = false;
                        }   
                    }

                    entity.GlobalPosition = startPosition.LinearInterpolate(moveTarget, timer / movePeriod);
                }
            }
        }
        
    }
        /// <summary>
        /// Returns the distance between the closest points on the line and the ray
        /// </summary>
        public static float LineRay(Vector2 lineOrigin, Vector2 lineDirection, Vector2 rayOrigin, Vector2 rayDirection)
        {
            Vector2 rayOriginToLineOrigin = lineOrigin - rayOrigin;
            float   denominator           = VectorE.PerpDot(lineDirection, rayDirection);
            float   perpDotA = VectorE.PerpDot(lineDirection, rayOriginToLineOrigin);

            if (Mathf.Abs(denominator) < Geometry.Epsilon)
            {
                // Parallel
                float perpDotB = VectorE.PerpDot(rayDirection, rayOriginToLineOrigin);
                if (Mathf.Abs(perpDotA) > Geometry.Epsilon || Mathf.Abs(perpDotB) > Geometry.Epsilon)
                {
                    // Not collinear
                    float rayOriginProjection = lineDirection.Dot(rayOriginToLineOrigin);
                    float distanceSqr         = rayOriginToLineOrigin.LengthSquared() - rayOriginProjection * rayOriginProjection;
                    // distanceSqr can be negative
                    return(distanceSqr <= 0 ? 0 : Mathf.Sqrt(distanceSqr));
                }
                // Collinear
                return(0);
            }

            // Not parallel
            float rayDistance = perpDotA / denominator;

            if (rayDistance < -Geometry.Epsilon)
            {
                // No intersection
                float   rayOriginProjection = lineDirection.Dot(rayOriginToLineOrigin);
                Vector2 linePoint           = lineOrigin - lineDirection * rayOriginProjection;
                return(linePoint.DistanceTo(rayOrigin));
            }
            // Point intersection
            return(0);
        }
Example #12
0
        public void Vect2_distTo_returnsdist()
        {
            Vector2 v1 = new Vector2(1, 2);
            Vector2 v2 = new Vector2(4, 6);
            double  d  = v1.DistanceTo(v2);

            Assert.AreEqual(5d, d);
        }
Example #13
0
 protected virtual void SlowDown()
 {
     velocity = velocity.LinearInterpolate(new Vector2(0, 0), .2f);
     if (velocity.DistanceTo(new Vector2(0, 0)) < 0.1f)
     {
         velocity = new Vector2(0, 0);
     }
 }
Example #14
0
        /// <summary>
        /// Update rover position and remove nodes from waypoints and planned path if the rover approaches them
        /// </summary>
        /// <param name="pose"></param>
        public void UpdatePose(RobotPose pose)
        {
            lock (plannerLock)
            {
                List <SimpleTreeNode <Vector2> > nodesToRemove = new List <SimpleTreeNode <Vector2> >();
                currentLocation = pose.ToVector2();
                //Remove waypoints from the list as the rover nears them
                nodesToRemove.Clear();
                foreach (SimpleTreeNode <Vector2> node in userWaypoints)
                {
                    if (currentLocation.DistanceTo(node.Value) < wayPointRadius)
                    {
                        nodesToRemove.Add(node);
                    }
                    else
                    {
                        break;
                    }
                }
                foreach (SimpleTreeNode <Vector2> node in nodesToRemove)
                {
                    userWaypoints.Remove(node);
                }

                //Remove nodes from the planned path as the rover approaches them
                lock (pathLock)
                {
                    nodesToRemove.Clear();
                    foreach (SimpleTreeNode <Vector2> node in outputNodeList)
                    {
                        if (currentLocation.DistanceTo(node.Value) < pathPointRadius)
                        {
                            nodesToRemove.Add(node);
                        }
                        else
                        {
                            break;
                        }
                    }
                    foreach (SimpleTreeNode <Vector2> node in nodesToRemove)
                    {
                        outputNodeList.Remove(node);
                    }
                }
            }
        }
Example #15
0
        private void Update()
        {
            if (Input.GetMouseButtonDown(1) && Vehicle.Unit.IsSelected && !InputManager.IsMouseInUI)
            {
                MakePathToPos(InputManager.MousePos, 0f, null, true);
            }

            if (!HasPath)
            {
                Movement.ForwardsThrust = 0f;
                Movement.Torque         = 0f;
            }
            else
            {
                TargetPoint point = Path[0];
                if (point.Position.DistanceCheck(transform.position, point.MinDistance))
                {
                    if (Path.Count != 1)
                    {
                        Path.RemoveAt(0);
                    }
                    else
                    {
                        float delta = Mathf.Abs(Mathf.DeltaAngle(transform.eulerAngles.z, point.TargetAngle));
                        if (delta <= 10f)
                        {
                            // Path complete!
                            uponComplete?.Invoke(this.Vehicle, true);
                            uponComplete = null;
                            Path.RemoveAt(0);
                            return;
                        }
                    }
                }
                Vector2 currentPos   = transform.position;
                float   currentAngle = transform.eulerAngles.z;
                float   dst          = currentPos.DistanceTo(point.Position);

                float finalCurveP = Mathf.Clamp01(dst / (ThrustDecreaseDistance * 0.5f));
                float finalAngle  = Mathf.LerpAngle(point.TargetAngle, currentPos.AngleTowards(point.Position), finalCurveP);

                float angle      = Path.Count == 1 ? finalAngle : currentPos.AngleTowards(point.Position);
                float deltaAngle = Mathf.DeltaAngle(currentAngle, angle);
                float scale      = Mathf.Abs(deltaAngle) / TorqueAngleMax;

                float torque = TorqueForce * scale * (deltaAngle > 0f ? 1f : -1f);
                float thrust = ThrustForce * Mathf.Clamp01(dst / ThrustDecreaseDistance);

                if (Path.Count == 1 && Movement.Body.velocity.sqrMagnitude > 1f)
                {
                    thrust *= -1f;
                }

                Movement.ForwardsThrust = thrust;
                Movement.Torque         = torque;
            }
        }
Example #16
0
    public override void _Process(float delta)
    {
        Vector2 newPos = (GetPosition() + dir * speed * delta);
        float   dist   = GetPosition().DistanceTo(newPos);

        SetPosition(newPos);


        float progress = origin.DistanceTo(GetPosition()) / origin.DistanceTo(targetPos);

        pellet.SetPosition(QuadraticBezier(new Vector2(0, 0), new Vector2(50 * -dir.y, 50 * -dir.x), new Vector2(0, 0), progress));
        pellet.SetScale(QuadraticBezier(new Vector2(1, 1), new Vector2(1.5f, 1.5f), new Vector2(1, 1), progress));


        if (origin.DistanceTo(targetPos) <= origin.DistanceTo(GetPosition()))
        {
            Hit();
        }
    }
Example #17
0
        public static float DistanceToSegment(this Vector2 point, Vector2 p0, Vector2 p1)
        {
            var v  = p1 - p0;
            var w  = point - p0;
            var c1 = w.DotProduct(v);
            var c2 = v.DotProduct(v);

            if (c1 < 0)
            {
                return(point.DistanceTo(p0));
            }
            if (c2 <= c1)
            {
                return(point.DistanceTo(p1));
            }

            var b  = c1 / c2;
            var pb = p0 + v * b;

            return(point.DistanceTo(pb));
        }
Example #18
0
    public override void _Process(float delta)
    {
        direction = new Vector2(0, 0);
        speed     = 0;

        if (Input.IsActionPressed("moveUp"))
        {
            direction.y = -1;
        }
        else if (Input.IsActionPressed("moveDown"))
        {
            direction.y = 1;
        }

        if (Input.IsActionPressed("moveLeft"))
        {
            direction.x = -1;
        }
        else if (Input.IsActionPressed("moveRight"))
        {
            direction.x = 1;
        }


        if (!isMoving && direction != new Vector2(0, 0))
        {
            targetDirection = direction;
            Console.WriteLine("checking file is vacant.");
            if (grid.IsCellVacant(GetPosition(), targetDirection))
            {
                targetPos = grid.UpdateChildPos(GetPosition(), direction, type);
                isMoving  = true;
            }
        }
        else if (isMoving)
        {
            speed    = MAX_SPEED;
            velocity = speed * targetDirection * delta;
            Console.WriteLine("cDir = " + direction.x + ":" + direction.y);
            Console.WriteLine("tDir = " + targetDirection.x + ":" + targetDirection.y);

            Vector2 position         = GetPosition();
            float   distanceToTarget = position.DistanceTo(targetPos);
            float   moveDistance     = velocity.Length();
            if (moveDistance > distanceToTarget)
            {
                velocity = targetDirection.Normalized() * distanceToTarget; //only normalize speed
                isMoving = false;
            }
            MoveAndCollide(velocity);
        }
    }
Example #19
0
    /// <summary>
    /// Calculate Euclidean distance between a point and a finite line segment.
    /// </summary>
    ///
    /// <param name="point">The point to calculate the distance to.</param>
    ///
    /// <returns>Returns the Euclidean distance between this line segment and the specified point. Unlike
    /// <see cref="Line2D.DistanceToPoint"/>, this returns the distance from the finite segment. (0,0) is 5 units
    /// from the segment (0,5)-(0,8), but is 0 units from the line through those points.</returns>
    ///
    public float DistanceToPoint(Vector2 point)
    {
        float segmentDistance;

        switch (LocateProjection(point))
        {
        case ProjectionLocation.RayA:
            segmentDistance = point.DistanceTo(_start);
            break;

        case ProjectionLocation.RayB:
            segmentDistance = point.DistanceTo(_end);
            break;

        default:
            segmentDistance = _line.DistanceToPoint(point);
            break;
        }
        ;

        return(segmentDistance);
    }
Example #20
0
    public override void _Process(float delta)
    {
        if (movePlatform)
        {
            movingPlatform = true;
            if (platformStartPos.DistanceTo(Position) < GetNode <Sprite>("Sprite").Texture.GetSize().x)
            {
                velocity         = new Vector2(speed, 0).Rotated(Rotation);
                velocity         = MoveAndSlide(velocity);
                platformExtended = true;
            }
            else
            {
                movingPlatform = false;
            }
        }
        else
        {
            movingPlatform = true;
            if (platformStartPos.DistanceTo(Position) > 1)
            {
                velocity         = new Vector2(-speed, 0).Rotated(Rotation);
                velocity         = MoveAndSlide(velocity);
                platformExtended = false;
            }
            else
            {
                movingPlatform = false;
            }
        }


        //if (!Input.IsActionPressed("click"))
        //{
        //    dragging = false;
        //    EmitSignal(nameof(Clicked), this, dragging);
        //}
    }
    public Tuple <Vector2, int> BackTrackPath(Vector2[] inPath, Vector2 startPos, float remainingDistance, int targeted)
    {
        int t = targeted;

        Vector2 pos = startPos;


        float dist = pos.DistanceTo(inPath[t - 1]);


        while (remainingDistance > dist)
        {
            if (t <= 1)
            {
                pos = inPath[0] + new Vector2(inPath[0] - inPath[1]).Normalized() * Math.Abs(remainingDistance);
                t   = 1;

                return(Tuple.Create(pos, t));
            }


            remainingDistance -= dist;
            t--;
            pos  = path[t];
            dist = pos.DistanceTo(inPath[t - 1]);
        }


        Vector2 spawnPos;

        float pr = remainingDistance / (pos.DistanceTo(path[t - 1]));

        spawnPos = pos.LinearInterpolate(path[t - 1], pr);



        return(Tuple.Create(spawnPos, t));
    }
Example #22
0
        public void Add(string text, Font font, Vector2 position, Color color, Vector2 scale, Vector2 origin, float rotation = 0)
        {
            Vector2 currentPosition = position;

            for (int i = 0; i < text.Length; i++)
            {
                int charCode = Convert.ToInt32(text[i]);
                if (charCode == 32) // space
                {
                    currentPosition.X += font.GetGlyph(32).Width *scale.X;
                    continue;
                }
                else if (charCode == 10) // \n
                {
                    currentPosition.X  = position.X;
                    currentPosition.Y += font.CellSize.Y * scale.Y;
                    continue;
                }
                else if (charCode == 9) // \t
                {
                    currentPosition.X += font.GetGlyph(32).Width *font.TabulatorFactor.X *scale.X;
                    continue;
                }
                else if (charCode == 11) // \v
                {
                    currentPosition.Y += font.CellSize.Y * font.TabulatorFactor.Y * scale.Y;
                    continue;
                }
                Font.GlyphInfo glyph = font.GetGlyph(charCode);
                if (rotation != 0)
                {
                    float distance = position.DistanceTo(currentPosition);
//#if FAST
                    Add(glyph.Texture, glyph.Area, position + new Vector2(GameMath.FCos(rotation) * distance, GameMath.FSin(rotation) * distance), color, scale, origin, rotation);
//#else
//                  float rot = GameMath.ToRadians(rotation);
//                  Add(glyph.Texture, glyph.Area, position + new Vector2((float)Math.Cos(rot) * distance, (float)Math.Cos(rot) * distance), color, scale, origin, rotation);
//#endif
                }
                else
                {
                    Add(glyph.Texture, glyph.Area, currentPosition, color, scale, origin, rotation);
                }
                currentPosition.X += glyph.Area.Size.X * scale.X;
                if (i < text.Length - 1)
                {
                    currentPosition.X += font.GetKerning(charCode, Convert.ToInt32(text[i + 1])) * scale.X;
                }
            }
        }
Example #23
0
    /// <summary>
    /// Calculate the velocity to keep distance behind the leader
    /// </summary>
    /// <param name="pLeaderPosition">the position of the node to follow</param>
    /// <param name="pFollowerPosition">the position of the follower</param>
    /// <param name="pFollowOffset">the distance to keep between the leader and follower node</param>
    /// <returns>A vector2 to represent the position to follow with the distance to keep</returns>
    public static Vector2 Steering_CalculateDistanceBetweenFollowers(Vector2 pLeaderPosition, Vector2 pFollowerPosition, float pFollowOffset)
    {
        // Get the vector direction to the leader (behind the leader)
        Vector2 direction = (pFollowerPosition - pLeaderPosition).Normalized();
        Vector2 velocity  = pFollowerPosition - (direction * pFollowOffset);

        // To avoid the follower to be too close to the leader (or it will have a kind of Parkinson movement)
        if (pLeaderPosition.DistanceTo(pFollowerPosition) <= pFollowOffset)
        {
            velocity = pFollowerPosition;
        }

        return(velocity);
    }
Example #24
0
    /// <summary>
    /// Calculate a velocity to move a character away from a destination (Run away)
    /// </summary>
    /// <param name="pVelocity">the actual velocity of the character</param>
    /// <param name="pPosition">the actual global position of the character</param>
    /// <param name="pTargetPosition">the destination of the character</param>
    /// <param name="pMaxSpeed">the maximum speed the character can reach</param>
    /// <param name="pFleeRadius">the circle radius where the character stop to flee</param>
    /// <param name="pMass">to slow down the character</param>
    /// <returns>A vector2 to represent the destination velocity or a Vector2(0,0) if character is away to the target</returns>
    public static Vector2 Steering_Flee(Vector2 pVelocity, Vector2 pPosition, Vector2 pTargetPosition,
                                        float pMaxSpeed = STEERING_DEFAULT_MAXSPEED, float pFleeRadius = STEERING_DEFAULT_FLEE, float pMass = STEERING_DEFAULT_MASS)
    {
        // If the target is outside the radius, do nothing
        if (pPosition.DistanceTo(pTargetPosition) >= pFleeRadius)
        {
            return(VECTOR_0);
        }

        // Use the formula to get the shortest path possible to run away from the target, then apply steering
        Vector2 desire_velocity = (pPosition - pTargetPosition).Normalized() * pMaxSpeed;

        return(_CalculateSteering(desire_velocity, pVelocity, pMass));
    }
Example #25
0
    // Kick off a new screenshake effect.
    public void Shake(float duration, float frequency, float amplitude, Vector2 rootPosition)
    {
        // Initialize variables.
        this.duration  = duration;
        timer          = duration;
        periodInMs     = 1f / frequency;
        this.amplitude = amplitude / Mathf.Max(1, rootPosition.DistanceTo(GlobalPosition) / 128);
        previousX      = (float)GD.RandRange(-1, 1);
        previousY      = (float)GD.RandRange(-1, 1);

        // Reset previous offset, if any.
        Offset    -= lastOffset;
        lastOffset = Vector2.Zero;
    }
Example #26
0
 public EntityBase GetNearestEntity(Vector2 position, float radius = 10f)
 {
     EntityBase mBase = null;
     double nearestDistance = double.MaxValue;
     foreach(EntityBase entBase in this.entityList)
     {
         double dist = position.DistanceTo(entBase.position);
         if(dist <= radius)
         {
             nearestDistance = dist;
             mBase = entBase;
         }
     }
     return mBase;
 }
Example #27
0
    private void MoveAlongPath(float distance)
    {
        //If the enemy is close to the target he stops moving
        if (((Node2D)GetParent()).Position.DistanceTo(target.Position) < 35)
        {
            if (!canAttack)
            {
                return;
            }
            //We set the path to null and the n break from the loop
            HitEvent hei = new HitEvent();
            hei.attacker = (Node2D)GetParent();
            hei.target   = target;
            hei.damage   = 5;
            hei.FireEvent();

            canAttack = false;
            attackTimer.Start();

            path = null;
            return;
        }

        //Stop the attack timer becuase the target has moved out of range
        attackTimer.Stop();

        Vector2 startPoint = ((Node2D)GetParent()).Position;

        foreach (Vector2 point in path)
        {
            float distanceToNextPoint = startPoint.DistanceTo(point);

            if (distance <= distanceToNextPoint && distance >= 0.0f)
            {
                ((Node2D)GetParent()).Position = startPoint.LinearInterpolate(point, distance / distanceToNextPoint);
                break;
            }
            else if (distance < 0.0f)
            {
                SetProcess(false);
                break;
            }

            distance  -= distanceToNextPoint;
            startPoint = point;
            path       = path.Skip(1).ToArray();
        }
    }
Example #28
0
    public void OnJointExpired(Joint.Type type, Vector2 expected)
    {
        Vector2 real;

        switch (type)
        {
        case Joint.Type.NOSE:  real = _Coords.Nose;   break;

        case Joint.Type.RHAND: real = _Coords.RWrist; break;

        case Joint.Type.LHAND: real = _Coords.LWrist; break;

        default: real = new Vector2(); break;
        }
        Score.Step((int)real.DistanceTo(expected));
    }
Example #29
0
        public override void Run(float delta)
        {
            if (_positionToReturn.DistanceTo(Node.Position) < 5)
            {
                Node.PopState();
                return;
            }

            var targetDirection = _positionToReturn - Node.Position;

            targetDirection = targetDirection.Normalized();

            var newVelocity = Node.Velocity.MoveToward(targetDirection * Node.MaxSpeed, Node.Acceleration * delta);

            Node.ApplyVelocity(newVelocity);
        }
    public List <Vector2> GetTargetTilesInArea(Vector2 centerPoint, int targetTileID, int maxRange)
    {
        var listOfTiles = floor.GetUsedCellsById(targetTileID); //This returns an array of vector 2's

        List <Vector2> validTiles = new List <Vector2>();

        // Godot.Collections.Array<Vector2> validTiles = new Godot.Collections.Array<Vector2>();
        foreach (Vector2 point in floor.GetUsedCellsById(targetTileID))
        {
            if (centerPoint.DistanceTo(point) < (float)maxRange)
            {
                validTiles.Add(point);
            }
        }

        return(validTiles);
    }
Example #31
0
        public Vector2[] Intersect(Circle circle)
        {
            double d = center.DistanceTo(circle.center);

            // check if there is any possibility of intersection
            if (d > r + circle.r)
            {
                return(emptyCoords);
            }
            // check if they are the same centers
            else if (center.Equals(circle.center))
            {
                return(emptyCoords);
            }
            // check if one is completely interned by the other
            else if (d + r < circle.r || d + circle.r < r)
            {
                return(emptyCoords);
            }
            else
            {
                // there is at least one intersection
                // assume that the circle are both lying on the x-axis to simplify analysis
                double R2 = circle.r * circle.r;
                double r2 = r * r;
                double d2 = d * d;

                double x = (d2 - r2 + R2) / (2 * d);
                double y = Math.Sqrt(R2 - x * x);

                // check if y is close to 0, indicating that this is only one hit
                if (y < 1e-10)
                {
                    return(new Vector2[] { circle.center + r * (center - circle.center).Normalize() });
                }
                else
                {
                    Vector2 vec    = (center - circle.center).Normalize();
                    Vector2 nom_pt = circle.center + x * vec;

                    Vector2 perp_vec = vec.Rotate90();
                    return(new Vector2[] { nom_pt + y * perp_vec, nom_pt - y * perp_vec });
                }
            }
        }
Example #32
0
 private double FindDistance_linear(Vector2 point, int px, int py)
 {
     return point.DistanceTo(new Vector2(px + 0.5, py + 0.5));
 }