I'm trying to make a boolean method that will return true if actor 1 can see actor 2 (no obstacles between them). My approach was to get x1 and y1 of actor 1, and x2 and y2 of actor 2. Once I have those, calculate the linear equation, then just do a for() loop from x1 through x2, checking for obstacles each time.
One major problem though, for some reason I seem incapable of calculating a linear equation via code. Here are two attempts I made:
Firstly with Slope-Intercept form: y = mx + b
Then again with Two-Point form: y - y1 = ((y2 - y1)/(x2 - x1)) * (x - x1)
All seems fine to me, but if I use System.out.println() to check the values, I end up with nowhere near what I expect. I've even tried just entering test coordinates on a graphing calculator and I end up with a graph far off from the original coordinates.
Any idea what's going on? Any help is appreciated.
1 2 3 4 5 6 7 8 9 | double yDiff = y2 - y1; double xDiff = x2 - x1; if (xDiff == 0 ) xDiff = xDiff + 0.000001 ; //assures it will not be 0 double m = yDiff/xDiff; double b = y2 - (m * x2); for ( int x = Math.min(( int )x2, ( int )x1); x < Math.max(( int )x2, ( int )x1); x++) { int y = ( int )((m * x) + b); //then the check for obstacles at (x, y) } |
1 2 3 4 5 | for ( int x = Math.min(( int )x2, ( int )x1); x < Math.max(( int )x2, ( int )x1); x++) { int y = ( int ) ((((y2 - y1)/(x2 - x1)) * (x - x1)) + y1); //then the check for obstacles at (x, y) | |