Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Created October 17, 2018 20:24
Show Gist options
  • Select an option

  • Save alexesDev/752a8929b4a1ccb856b46d60b0b2f477 to your computer and use it in GitHub Desktop.

Select an option

Save alexesDev/752a8929b4a1ccb856b46d60b0b2f477 to your computer and use it in GitHub Desktop.
function calculateInterceptShotPosition(pShooter, pTarget0, vTarget, sProjectile)
local R = pTarget0 - pShooter
local a = vTarget.x^2 + vTarget.y^2 - sProjectile^2
local b = 2 * (R.x * vTarget.x + R.y * vTarget.y)
local c = R.x^2 + R.y^2
if R:len2() < 1 then
return nil
end
if math.abs(a) < 1 then
if math.abs(b) < 1 then
return nil
end
return -c/b;
end
local discriminant = b*b - 4 * a * c;
if discriminant < 0 then
return nil
end
if discriminant > 0 then
local quad = math.sqrt(discriminant);
local t1 = (-b + quad)/(2*a);
local t2 = (-b - quad)/(2*a);
if (t1 < 0) and (t2 < 0) then
return nil
elseif t2 < 0 and t1 >= 0 then
return t1
elseif t1 < 0 and t2 >= 0 then
return t2
elseif t1 < t2 then
return t1
else
return t2
end
end
return -b / (2*a);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment