t8rt0t

blib.lua

Jul 8th, 2024 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.27 KB | None | 0 0
  1. local G = -0.05
  2. local DRAG = 0.99
  3. local b = {
  4.     G = G,
  5.     DRAG = DRAG,
  6.     void_level = -128,
  7.     reentry_level = 600
  8. }
  9.  
  10. local function interp(p1,p2,y)
  11.     return p1[1] + (p2[1]-p1[1])/(p2[2]-p1[2])*(y-p1[2])
  12. end
  13.  
  14. function b.tick(p,v)
  15.     v[1],v[2] = v[1]*DRAG,v[2]*DRAG + G
  16.     p[1],p[2] = p[1] + v[1],p[2]+v[2]
  17. end
  18.  
  19. function b.simulate(angleRad,nCannonLength,nPowderCharges,tY)
  20.     local v = {nPowderCharges*2*math.cos(angleRad),nPowderCharges*2*math.sin(angleRad)}
  21.     local p = {nCannonLength*math.cos(angleRad),nCannonLength*math.sin(angleRad)}
  22.     local t = 0
  23.     while v[2] >= 0 or p[2] > tY do
  24.         local last_pos = {p[1],p[2]}
  25.         b.tick(p,v)
  26.         if (last_pos[2] > tY) ~= (p[2] > tY) then
  27.             return interp(last_pos,p,tY),t
  28.         end
  29.         t = t+1
  30.     end
  31. end
  32.  
  33. function b.getAngle(tX,tY,nCannonLength,nPowderCharges,err)
  34.     err = tonumber(err) or 0.1
  35.     local angle = 0
  36.     local hit,tick = b.simulate(angle,nCannonLength,nPowderCharges,tY)
  37.     local lastType
  38.     local increment = 0.1
  39.     for i=1,10 do --70s, might be too long for good calculations
  40.         local res = {pcall(function()
  41.                     while true do
  42.                         if not hit or hit < tX - err then --undershoot -> increase angle
  43.                             if lastType == "overshoot" then increment = increment * 0.5 end
  44.                             angle = angle + increment
  45.                             lastType = "undershoot"
  46.                         elseif hit > tX + err then --overshoot decrease angle
  47.                             if lastType == "undershoot" then increment = increment * 0.5 end
  48.                             angle = angle - increment
  49.                             lastType = "overshoot"
  50.                         else
  51.                             return true,{pitch=angle,simulatedHit={hit,tY},flightTicks=tick}
  52.                         end
  53.                         if angle < -math.pi/6 or angle >= math.pi/3 then return false,"No suitable angle found for the landing" end
  54.                         hit,tick = b.simulate(angle,nCannonLength,nPowderCharges,tY)
  55.                     end
  56.                 end)}
  57.         if table.remove(res,1) then return unpack(res) end
  58.         sleep(0)
  59.     end
  60.     return false,"timed out"
  61. end
  62.  
  63. return b
Advertisement
Add Comment
Please, Sign In to add comment