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 srcPos, float speed, Vector2f dstPos, Vector2f dstVel) {
- Vector2f t = new Vector2f(dstPos.x - srcPos.x, dstPos.y - srcPos.y);
- Vector2f tv = new Vector2f(dstVel);
- float a = tv.x * tv.x + tv.y * tv.y - speed * speed;
- float b = 2 * (tv.x * t.x + tv.y * t.y);
- float c = t.x * t.x + t.y * t.y;
- Vector2f ts = quad(a, b, c);
- Vector2f sol = null;
- if (ts != null) {
- float ti = Math.min(ts.x, ts.y);
- if (ti < 0) {
- ti = Math.max(ts.x, ts.y);
- }
- if (ti > 0) {
- sol = new Vector2f(dstPos.x + dstVel.x * ti, dstPos.y + dstVel.y * ti);
- }
- }
- return sol;
- }
- public static Vector2f quad(float a, float b, float c) {
- Vector2f sol = null;
- if (Float.compare(Math.abs(a), 0) == 0) {
- if (Float.compare(Math.abs(b), 0) == 0) {
- sol = (Float.compare(Math.abs(c), 0) == 0) ? new Vector2f(0, 0) : null;
- } else {
- sol = new Vector2f(-c / b, -c / b);
- }
- } else {
- float disc = b * b - 4 * a * c;
- if (disc >= 0) {
- disc = (float) Math.sqrt(disc);
- a = 2 * a;
- sol = new Vector2f((-b - disc) / a, (-b + disc) / a);
- }
- }
- return sol;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement