CupCode Gamers
From the Cup, to the Code, for the Gamers
  • News
  • Games and Apps
    • Baseball Score Tracker
    • Droplets
    • Jet Fighter
    • Jet Fighter Neon
    • Short Circuit
    • ThaumCheater
    • Tic-Tac-Toe
    • Zombie Swarm
  • Other Pages
    • Facebook
    • Itch-IO
    • Surviving Ars Magica 2
    • Steam Group
    • YouTube Channel
  • Sneaky Peeky
  • C# Tutorials
  • About Us
  • Policies
  • Contact Us

Moving a unit towards a point with movement range

3/24/2017

These two variables will hold the desired X,Y coordinates for the limited move

float MoveLimitedX;
float MoveLimitedY;

These are the variables being used in the calculations MovementRadius is the distance the unit is allowed to move from it’s starting point

float MovementRadius = 4f;

This is the X and Y coordinates for the unit that’s moving

float UnitX = 6f;
float UnitY = 0f;

These are the x and y coordinates for the target that the unit is moving towards

float TargetX = 0f;
float TargetY = 8f;

With two points, we’re imagining a triangle being formed from the unit to the target with the third point as a virtual point created where the axis from both points meet. This forms a right triangle with the line between the unit and the target as the hypotenuse, so we’ll first calculate the hypotenuse. This uses pythagoreums theorum of A^2 + B^2 = C^2

float hypotenuse = System.Math.Sqrt(((UnitX - TargetX) ^ 2) + ((UnitY - TargetY) ^ 2));

Now that we have the hypotenuse, we can calculate the x and y coordinates for the limited move. In case you can’t tell, we’re actually calculating Sine and multiplying it by MovementRadius to get MoveLimitedY, and we’re calculating Cosine and multiplying it by MovementRadius to get MoveLimitedX

MoveLimitedX = UnitX - (((UnitX - TargetX) / hypotenuse) * MovementRadius);
MoveLimitedY = UnitY - (((UnitY - TargetY) / hypotenuse) * MovementRadius);

MoveLimitedX should be equal to 3.6, and MoveLimitedY should be equal to 3


Respond

Copyright © 2020 CupCode Gamers / Jason Yarber

Privacy Policy