Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Algorithm by broofa @ stackoverflow.com
- // Returns position of where the projectile should head towards to hit the target
- // Returns null if the projectile can never hit the target
- public static Vector2f intercept(Vector2f point, float speed, Vector2f target, Vector2f targetVel) {
- Vector2f difference = new Vector2f(target.x - point.x, target.y - point.y);
- float a = targetVel.x * targetVel.x + targetVel.y * targetVel.y - speed * speed;
- float b = 2 * (targetVel.x * difference.x + targetVel.y * difference.y);
- float c = difference.x * difference.x + difference.y * difference.y;
- Vector2f solutionSet = quad(a, b, c);
- Vector2f intercept = null;
- if (solutionSet != null) {
- float bestFit = Math.min(solutionSet.x, solutionSet.y);
- if (bestFit < 0) {
- bestFit = Math.max(solutionSet.x, solutionSet.y);
- }
- if (bestFit > 0) {
- intercept = new Vector2f(target.x + targetVel.x * bestFit, target.y + targetVel.y * bestFit);
- }
- }
- return intercept;
- }
- public static Vector2f quad(float a, float b, float c) {
- Vector2f solution = null;
- if (Float.compare(Math.abs(a), 0) == 0) {
- if (Float.compare(Math.abs(b), 0) == 0) {
- solution = (Float.compare(Math.abs(c), 0) == 0) ? new Vector2f(0, 0) : null;
- } else {
- solution = new Vector2f(-c / b, -c / b);
- }
- } else {
- float d = b * b - 4 * a * c;
- if (d >= 0) {
- d = (float) Math.sqrt(d);
- a = 2 * a;
- solution = new Vector2f((-b - d) / a, (-b + d) / a);
- }
- }
- return solution;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement