Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DavidMcLaughlin208/60e69e698e3858617c322d80a8f174e2 to your computer and use it in GitHub Desktop.
Save DavidMcLaughlin208/60e69e698e3858617c322d80a8f174e2 to your computer and use it in GitHub Desktop.
Algorithm to move from one point on a 2D matrix to another in the shortest most logical route
public void iterateAndApplyMethodBetweenTwoPoints(Vector2 pos1, Vector2 pos2, Supplier<FunctionInput> function) {
// If the two points are the same no need to iterate. Just run the provided function
if (pos1.epsilonEquals(pos2)) {
function.invoke();
return;
}
int matrixX1 = pos1.x;
int matrixY1 = pos1.y;
int matrixX2 = pos2.x;
int matrixY2 = pos2.y;
int xDiff = matrixX1 - matrixX2;
int yDiff = matrixY1 - matrixY2;
boolean xDiffIsLarger = Math.abs(xDiff) > Math.abs(yDiff);
int xModifier = xDiff < 0 ? 1 : -1;
int yModifier = yDiff < 0 ? 1 : -1;
int longerSideLength = Math.max(Math.abs(xDiff), Math.abs(yDiff));
int shorterSideLength = Math.min(Math.abs(xDiff), Math.abs(yDiff));
float slope = (shorterSideLength == 0 || longerSideLength == 0) ? 0 : ((float) (shorterSideLength) / (longerSideLength));
int shorterSideIncrease;
for (int i = 1; i <= longerSideLength; i++) {
shorterSideIncrease = Math.round(i * slope);
int yIncrease, xIncrease;
if (xDiffIsLarger) {
xIncrease = i;
yIncrease = shorterSideIncrease;
} else {
yIncrease = i;
xIncrease = shorterSideIncrease;
}
int currentY = matrixY1 + (yIncrease * yModifier);
int currentX = matrixX1 + (xIncrease * xModifier);
if (isWithinBounds(currentX, currentY)) {
function.invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment