Greetings.
So I have been profiling my code, and I have smoothed out almost all of the rough edged. I have this one though that kinda baffles me.
I have a function that returns a series of points when drawing a line. Kind of like an itinerary of points. It is used for several things. I use it to calculate a projectile’s path, and I also use it to calculate line of sight. Lots of stuff.
Problem is it sucks. I am guessing a large part of the suckiness is the allocating of new points in the loop as the path grows.
Can some nice person on here help me optimize it, or give me ideas on how I could optimize it myself?
public static void calc_line(ArrayList<RPGUtil.point> xitinerary,RPGUtil.point source, RPGUtil.point dest, int max_size)
{
RPGUtil.point lp;
xitinerary.clear();
int x2 = dest.x;
int y2 = dest.y;
int x = source.x;
int y = source.y;
int dx = Math.abs(x2 - x), sx = x < x2 ? 1 : -1;
int dy = Math.abs(y2 - y), sy = y < y2 ? 1 : -1;
int err = (dx>dy ? dx : -dy)/2;
while (!(x == x2 && y == y2))
{
lp = new RPGUtil.point(x,y);
xitinerary.add(lp);
if ( (max_size !=0 ) && (xitinerary.size() >= max_size) )
{
xitinerary.clear();
break;
}
int e2 = err;
if (e2 > -dx)
{
err -= dy;
x += sx;
}
if (e2 < dy)
{
err += dx;
y += sy;
}
}
}