Created
June 28, 2016 07:19
-
-
Save tyrcho/a38d4e1070eff2179cb80eb43584650e to your computer and use it in GitHub Desktop.
Quadratic equation to find the interception point of 2 moving targets. http://gamedev.stackexchange.com/questions/25277/how-to-calculate-shot-angle-and-velocity-to-hit-a-moving-target
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math._ | |
object QuadraticInterception extends App { | |
val me = Pos(100, 100) | |
val tgt = Pos(400, 400) | |
val tgtDirection = Pos(0, -100) | |
println(me.intercept(tgt, tgtDirection)) | |
case class Pos(x: Int, y: Int) { | |
def dist2(p: Pos) = sqr(x - p.x) + sqr(y - p.y) | |
def dist(p: Pos) = sqrt(dist2(p)) | |
def +(p: Pos) = Pos(x + p.x, y + p.y) | |
def -(p: Pos) = Pos(x - p.x, y - p.y) | |
def /(i: Int) = Pos(x / i, y / i) | |
def *(i: Double) = Pos((x * i).toInt, (y * i).toInt) | |
def scalar(p: Pos) = x * p.x + y * p.y | |
def intercept(tgt: Pos, tgtDirection: Pos): Option[Pos] = { | |
val mySpeed = 99 | |
val tgtSpeed = 100 | |
val toTarget = tgt - this | |
val a = sqr(tgtSpeed) - sqr(mySpeed) | |
val b = 2 * (tgtDirection scalar toTarget) | |
val c = toTarget scalar toTarget | |
val p = -b / (2.0 * a) | |
val q = sqrt(sqr(b) - 4 * a * c) / (2 * a) | |
val t1 = p - q | |
val t2 = p + q | |
if (t1 > 0 || t2 > 0) { | |
val t = if (t1 > t2 && t2 > 0) t2 else t1 | |
val aimSpot = tgt + tgtDirection * t | |
Some(aimSpot) | |
} else None | |
} | |
} | |
def sqr(i: Long) = i * i | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment