hansi wrote on Jun 16th, 2010, 2:16am:thanks for the suggestions, i've already updated the code.
it was two in the morning yesterday and i really couldn't be bothered to go through the code again after i had it working ...
Believe me, I know that feeling!
Glad I could help.
Two other things that occurred to me about this part:
Code:
float dx = x2 - x1;
float dy = y2 - y1;
float d = sqrt( dx*dx + dy*dy );
float ca = dx/d;
float sa = dy/d;
float mX = (-x1+x)*ca + (-y1+y)*sa;
float mY = (-y1+y)*ca + ( x1-x)*sa;
First, if you made all the changes I suggested, then you no longer need mY, so you can leave that out.
Second, the variables dx, dy, d, ca, and sa depend only on the endpoints of the line (x1, x2, y1, y2), not on the point (x, y), so you can save time by calculating them when you set a new line, and then re-use the same values until you change the location of the endpoints. So, for example:
Code:
// after setting a new x1, x2, y1, y2:
PVector point1 = new PVector(x1, y1, 0);
PVector lineUnit = new PVector(x2 - x1, y2 - y1, 0);
float d = lineUnit.mag();
lineUnit.normalize();
This uses d to store the length of the line. The normalize() method shortens or lengthens lineUnit to a length of 1, pointing in the same direction--so afterwards, lineUnit is simply [cos(a), sin(a), 0] where a is the angle the line points (from point 1 to point 2).
Then you can change getDistance() to work something like this:
Code:
PVector getDistance(float x1, float x2, PVector lineUnit, float d, float x, float y) {
float ca = lineUnit.x;
float sa = lineUnit.y;
// proceed as before...
}