Skip to content

Instantly share code, notes, and snippets.

@tedigc
Created September 16, 2017 15:44
Show Gist options
  • Save tedigc/f81af98325b3348f456304dbd1e986d2 to your computer and use it in GitHub Desktop.
Save tedigc/f81af98325b3348f456304dbd1e986d2 to your computer and use it in GitHub Desktop.
calculate a line of points between two vectors
static public ArrayList<Vector2> line(Vector2 v1, Vector2 v2) {
int x = (int) v1.x;
int y = (int) v1.y;
int x2 = (int) v2.x;
int y2 = (int) v2.y;
ArrayList<Vector2> result = new ArrayList<Vector2>();
int w = x2 - x ;
int h = y2 - y ;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
int longest = Math.abs(w) ;
int shortest = Math.abs(h) ;
if (!(longest>shortest)) {
longest = Math.abs(h) ;
shortest = Math.abs(w) ;
if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
result.add(new Vector2(x, y));
numerator += shortest ;
if (!(numerator<longest)) {
numerator -= longest ;
x += dx1 ;
y += dy1 ;
} else {
x += dx2 ;
y += dy2 ;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment