Advertisement
DarkRevenant

Untitled

Apr 19th, 2014
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 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 point, float speed, Vector2f target, Vector2f targetVel) {
  5.         Vector2f difference = new Vector2f(target.x - point.x, target.y - point.y);
  6.  
  7.         float a = targetVel.x * targetVel.x + targetVel.y * targetVel.y - speed * speed;
  8.         float b = 2 * (targetVel.x * difference.x + targetVel.y * difference.y);
  9.         float c = difference.x * difference.x + difference.y * difference.y;
  10.  
  11.         Vector2f solutionSet = quad(a, b, c);
  12.  
  13.         Vector2f intercept = null;
  14.         if (solutionSet != null) {
  15.             float bestFit = Math.min(solutionSet.x, solutionSet.y);
  16.             if (bestFit < 0) {
  17.                 bestFit = Math.max(solutionSet.x, solutionSet.y);
  18.             }
  19.             if (bestFit > 0) {
  20.                 intercept = new Vector2f(target.x + targetVel.x * bestFit, target.y + targetVel.y * bestFit);
  21.             }
  22.         }
  23.  
  24.         return intercept;
  25.     }
  26.  
  27.     public static Vector2f quad(float a, float b, float c) {
  28.         Vector2f solution = null;
  29.         if (Float.compare(Math.abs(a), 0) == 0) {
  30.             if (Float.compare(Math.abs(b), 0) == 0) {
  31.                 solution = (Float.compare(Math.abs(c), 0) == 0) ? new Vector2f(0, 0) : null;
  32.             } else {
  33.                 solution = new Vector2f(-c / b, -c / b);
  34.             }
  35.         } else {
  36.             float d = b * b - 4 * a * c;
  37.             if (d >= 0) {
  38.                 d = (float) Math.sqrt(d);
  39.                 a = 2 * a;
  40.                 solution = new Vector2f((-b - d) / a, (-b + d) / a);
  41.             }
  42.         }
  43.         return solution;
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement