What’s the best way of find a line’s length, subtracting one Point from another seems clunky and I can’t see an inbuilt method in Line2D, is there a better way?
What about the elementary line distance formula which you should have learned in middle school/early high school? (unless you’re younger :o)
sqrt((x1-x2) ^ 2 + (y1-y2) ^ 2)
double distance = Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2));
Also, the following static methods exist:
Point2D.distance(double x1, double y1, double x2, double y2)
Point2D.distanceSq(double x1, double y1, double x2, double y2)
…
Yes, not taking the square root if you don’t have to is a nice optimization, but the question was about finding distance. Let’s not confuse people unnecessarily…
I have to agree with sproingie: I think optimizing out Math.sqrt(…) and replacing it with two Math.pow(…)'s is offtopic, confusing and hilarious. Not to mention the if/else blocks that return false and true
thanks, I’ll use the solution from Point2D methinks, much easier to use and get my tiny brain around
Ehh I know it may have been a little too off topic but I think he would have been able to figure it out in like 2 secs from the formula and the 2 Math.pows was because I was lazy and hate typing code into a post.
In my actual code I try to use as little possible from the Math class. And sorry if it was too confusing…I am not the best at explaining things.
If you want to avoid square root in collision, try to check both X and Y first without bring them to pythagoras.
Because typing: Math.pow(x,2) is shorter than x*x?
To be fair, in his example that would be:
Math.pow((x1-x2),2)
(x1-x2)*(x1-x2)
which still proves your point
Geez normally I don’t take offense to stuff but man it really seems like I must have come across rude or something because you guys are down my throat here. I will admit that I was wrong in my earlier post that Math.pow or what ever is longer but come on now no need to point out the obvious error.
If it means that much to you guys I will change/remove my earlier posts so no one else will have to suffer from my horrible coding examples/posts. Just trying to help. :clue:
Don’t take it so personal.
There was a question, you answered it with something that actually did not solve his problem, introduced slow code for the sake of optimization, and then you defended it by saying you wanted to provide a short code sample, while the correct and faster version was shorter.
Can’t we point that out? We’re not out to pick on you, just responding to what you actually said…
All true.
Note that if you want the length/magnitude AND want short code then you can alway use hypot. But you don’t really want to do that in games because you shouldn’t care about overflow/underflow issues.