Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Created June 28, 2016 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyrcho/a38d4e1070eff2179cb80eb43584650e to your computer and use it in GitHub Desktop.
Save tyrcho/a38d4e1070eff2179cb80eb43584650e to your computer and use it in GitHub Desktop.
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