SpaceFight! trigonometry and limiting mobility

One of the “features” I wanted to include in SpaceFight! is a range of mobility for the player pawns. The units of measurement for the distance is arbitrary, and the screenshot below reflects 200 “units”.

That green circle surrounding the highlighted pawn shows the player the possible area they can place that pawn. The tricky part here was limiting the “potential new location” to never exceed the radius of that circle. Perhaps there was an easier way to do this, but I solved it with a little high school trigonometry.

Calculate distance

a^2 + b^2 = c^2

or

square root of (a^2 + b^2) = c

In this case, a = x1 – x2, and b = y1 – y2 (using cartesian coordinates)

dist = Math.sqrt(
Math.pow((getX() - getMouseX()), 2)
+
Math.pow((getY() - getMouseY()), 2)
);

If that value c exceeds the pawn’s range then find the coordinate of the intersect between the circle and the line drawn between the pawn and the mouse cursor.

Calculate angle

Now, to force the new location to be where the lines intersect we only need two things. First, the distance which is just the pawn’s range of mobility. Second, the angle between the pawn and the mouse cursor.

angleRadian = Math.atan2(
(getMouseY() - getY()) ,
(getMouseX() - getX())
);

Set the location

Now that we have the angle we can calculate the new location.

pX = getX() + range * Math.cos(angleRadian);
pY = getY() + range * Math.sin(angleRadian);
setNewLocation(pX, pY);

Now if the mouse is located outside the pawn’s range then the new location will always be somewhere along the edge of the pawn’s range.

Leave a Reply

 

Staypressed theme by Themocracy