Advertisement
DarkRevenant

Untitled

Apr 19th, 2014
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1.     // Algorithm by broofa @ stackoverflow.com
  2.     // Returns position of where the projectile should head towards to hit the target
  3.     // Returns null if the projectile can never hit the target
  4.     public static Vector2f intercept(Vector2f srcPos, float speed, Vector2f dstPos, Vector2f dstVel) {
  5.         Vector2f t = new Vector2f(dstPos.x - srcPos.x, dstPos.y - srcPos.y);
  6.         Vector2f tv = new Vector2f(dstVel);
  7.  
  8.         float a = tv.x * tv.x + tv.y * tv.y - speed * speed;
  9.         float b = 2 * (tv.x * t.x + tv.y * t.y);
  10.         float c = t.x * t.x + t.y * t.y;
  11.  
  12.         Vector2f ts = quad(a, b, c);
  13.  
  14.         Vector2f sol = null;
  15.         if (ts != null) {
  16.             float ti = Math.min(ts.x, ts.y);
  17.             if (ti < 0) {
  18.                 ti = Math.max(ts.x, ts.y);
  19.             }
  20.             if (ti > 0) {
  21.                 sol = new Vector2f(dstPos.x + dstVel.x * ti, dstPos.y + dstVel.y * ti);
  22.             }
  23.         }
  24.  
  25.         return sol;
  26.     }
  27.  
  28.     public static Vector2f quad(float a, float b, float c) {
  29.         Vector2f sol = null;
  30.         if (Float.compare(Math.abs(a), 0) == 0) {
  31.             if (Float.compare(Math.abs(b), 0) == 0) {
  32.                 sol = (Float.compare(Math.abs(c), 0) == 0) ? new Vector2f(0, 0) : null;
  33.             } else {
  34.                 sol = new Vector2f(-c / b, -c / b);
  35.             }
  36.         } else {
  37.             float disc = b * b - 4 * a * c;
  38.             if (disc >= 0) {
  39.                 disc = (float) Math.sqrt(disc);
  40.                 a = 2 * a;
  41.                 sol = new Vector2f((-b - disc) / a, (-b + disc) / a);
  42.             }
  43.         }
  44.         return sol;
  45.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement