Skip to content

Instantly share code, notes, and snippets.

@incinirate
Last active November 16, 2018 18:29
Show Gist options
  • Save incinirate/e7486cfd9f70427e4d3573ee0ffe2ba9 to your computer and use it in GitHub Desktop.
Save incinirate/e7486cfd9f70427e4d3573ee0ffe2ba9 to your computer and use it in GitHub Desktop.
Missile targeting algorithm via numeric approximation
local sqrt = math.sqrt
local cos, sin = math.cos, math.sin
local targetStep = 0.1 -- Determines targeting accuracy, lower is better (but slower)
local function targetAngle(missile, target)
local px = missile.pos.x
local py = missile.pos.y
local vx = missile.vel.x
local vy = missile.vel.y
local am = missile.accel
local tx = target.pos.x
local ty = target.pos.y
local tvx = 0
local tvy = 0
if target.vel then
tvx = target.vel.x
tvy = target.vel.y
end
local closestDist = math.huge
local closestAngle = math.pi / 2
for angle = 0, math.pi*2, targetStep do
local cosAngle = cos(angle)
local sinAngle = sin(angle)
local secA = 1 / cosAngle
local tFront = (tvx - vx) / (cosAngle * am)
local tHalf = sqrt(
(secA * (2 * am * (tx - px) + (tvx - vx)*(tvx - vx) * secA))
/
(am*am)
)
local t1 = tFront - tHalf
local t2 = tFront + tHalf
if t1 > 0 then
local xToBe = px + t1 * vx + (am * t1*t1 * cosAngle)/2
local yToBe = py + t1 * vy + (am * t1*t1 * sinAngle)/2
local xWillBe = tx + tvx*t1
local yWillBe = ty + tvy*t1
local dist = (xWillBe - xToBe)*(xWillBe - xToBe) + (yWillBe - yToBe)*(yWillBe - yToBe)
if dist < closestDist then
closestDist = dist
closestAngle = angle
end
end
if t2 > 0 then
local xToBe = px + t2 * vx + (am * t2*t2 * cosAngle)/2
local yToBe = py + t2 * vy + (am * t2*t2 * sinAngle)/2
local xWillBe = tx + tvx*t2
local yWillBe = ty + tvy*t2
local dist = (xWillBe - xToBe)*(xWillBe - xToBe) + (yWillBe - yToBe)*(yWillBe - yToBe)
if dist < closestDist then
closestDist = dist
closestAngle = angle
end
end
end
return closestAngle
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment