MegiRicky

ZTZ-99Aim

Oct 29th, 2024 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.77 KB | None | 0 0
  1. local radar = peripheral.find("sp_radar")
  2. local ar = peripheral.find("arController")
  3. local modem = peripheral.wrap("right")
  4. local yawMotor = peripheral.find("Create_RotationSpeedController")
  5. local cannonSourceChannel = 701
  6. local controlChannel = 500
  7. local holo = peripheral.find("hologram")
  8.  
  9. local function askUser(prompt, defaultValue)
  10. print(prompt .. " (default: " .. defaultValue .. ")")
  11. local input = io.read()
  12. if input == "" then
  13. return defaultValue
  14. else
  15. return input
  16. end
  17. end
  18.  
  19. local cannonControlMode = "mouseAim"
  20.  
  21. local screenWidth, screenHeight, fov, GUIscale
  22. local sourceX, sourceY, sourceZ = 0,0,0
  23. local source = {}
  24. local userID
  25. local friendlyIDs
  26. local friendlyIDFile = "friendly_ids.txt"
  27. local widthMagic = 1.125
  28. local projectionDistance = 30
  29. local currentPitch, currentYaw = 0,0
  30. local lastCurrentPitch, lastCurrentYaw = 0,0
  31. local lockedTarget = nil
  32. local elements = {}
  33. local pInfo = {}
  34. local cannonHitPos = {}
  35. local pitchAdjustments = "1"
  36. local lastYawUpdateTime = 0
  37. local lastPitchUpdateTime = 0
  38. local updateInterval = 0.01
  39. local projectileSpeed = 370
  40. local g = 0.04
  41. local cd = 0.99
  42. local vm
  43.  
  44. local yawErrorSum = 0
  45. local lastYawError = 0
  46. local pitchErrorSum = 0
  47. local lastPitchError = 0
  48. local yawError = 0
  49. local yawIntegral = 0
  50. local yawPrevError = 0
  51. local pitchError = 0
  52. local pitchIntegral = 0
  53. local pitchPrevError = 0
  54. local lastTime = os.clock()
  55.  
  56. local Kp_yaw = 0.35
  57. local Ki_yaw = 0
  58. local Kd_yaw = 0.05
  59. local Kp_pitch = 0.25
  60. local Ki_pitch = 0.05
  61. local Kd_pitch = 0.012
  62. local dt = 0.1
  63.  
  64. local turnFactor = 0
  65.  
  66. local controls = {cannonControlMode = "mouseAim"}
  67.  
  68.  
  69. -- Configuration file paths
  70. local function readConfig(filename)
  71. if not fs.exists(filename) then
  72. print("Configuration file '" .. filename .. "' does not exist. Creating it.")
  73. file = fs.open(filename, "w")
  74.  
  75. resolution = askUser("Input your resolution eg.(1920,1080)", "3440,1440")
  76. file.writeLine("resolution=" .. resolution)
  77.  
  78. fov = askUser("Input your FOV eg.(70)", "70")
  79. file.writeLine("fov=" .. fov)
  80.  
  81. userID = askUser("Input your ID", "MegiRicky")
  82. file.writeLine("userID=" .. userID)
  83.  
  84. -- Integrating channel number into the config
  85. cannonHitPosChannel = askUser("Input the cannon data channel number", "700")
  86. file.writeLine("cannonHitPosChannel=" .. cannonHitPosChannel)
  87.  
  88. controlChannel = askUser("Input the control channel", "500")
  89. file.writeLine("controlChannel=" .. controlChannel)
  90.  
  91. pitchCompensation = askUser("Input the pitchCompensation.(for when the plane and the computer is not on the same ship)","48.24")
  92. file.writeLine("pitchCompensation="..pitchCompensation)
  93.  
  94. file.close()
  95. end
  96. sleep(0.2)
  97. local file = fs.open(filename, "r")
  98. local config = {}
  99. local line = file.readLine()
  100. while line do
  101. local key, value = line:match("^(%w+)=(.*)$")
  102. config[key] = value
  103. line = file.readLine()
  104. end
  105. file.close()
  106. return config
  107. end
  108.  
  109. -- Function to edit configuration
  110. local function editConfig(filename)
  111. print("Do you want to edit the config? (yes/no),press enter to skip")
  112. local editChoice = io.read()
  113. if editChoice == "" then
  114. editChoice = "no"
  115. end
  116. if editChoice:lower() == "yes" then
  117. if fs.exists(filename) then
  118. fs.delete(filename)
  119. end
  120. return readConfig(filename)
  121. else
  122. return nil
  123. end
  124. end
  125.  
  126. -- Function to select or create config
  127. local function loadOrCreateConfig()
  128. print("Which player's config do you want to load?")
  129. local selectedID = io.read()
  130.  
  131. local configFile = selectedID .. "config.txt"
  132.  
  133. if fs.exists(configFile) then
  134. print("Config file for " .. selectedID .. " exists. Loading it.")
  135. local config = readConfig(configFile)
  136.  
  137. -- Ask if user wants to edit config
  138. editConfig(configFile)
  139.  
  140. return config
  141. else
  142. print("No config file found for " .. selectedID .. ". Creating a new one.")
  143. return readConfig(configFile)
  144. end
  145. end
  146.  
  147. -- Function to read friendly IDs from a file
  148. local function readFriendlyIDs(filename)
  149. if not fs.exists(filename) then
  150. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  151. local file = fs.open(filename, "w")
  152. print("Input friendly IDs separated by commas:")
  153. local ids = io.read()
  154. file.write(ids)
  155. file.close()
  156. end
  157.  
  158. local file = fs.open(filename, "r")
  159. local friendlyIDs = {}
  160. if file then
  161. local line = file.readLine()
  162. while line do
  163. for id in string.gmatch(line, "%d+") do
  164. table.insert(friendlyIDs, tonumber(id))
  165. end
  166. line = file.readLine()
  167. end
  168. file.close()
  169. end
  170. return friendlyIDs
  171. end
  172.  
  173. local function sign(x)
  174. return x > 0 and 1 or x < 0 and -1 or 0
  175. end
  176.  
  177. -- Load configuration
  178.  
  179. local config = loadOrCreateConfig()
  180. sleep(0.2)
  181. print(textutils.serialize(config))
  182. screenWidth, screenHeight = config.resolution:match("(%d+),(%d+)")
  183. screenWidth = tonumber(screenWidth)
  184. screenHeight = tonumber(screenHeight)
  185. fov = tonumber(config.fov)
  186. GUIscale = 4
  187. local mode = tonumber(config.mode)
  188. userID = config.userID
  189. friendlyIDs = readFriendlyIDs(friendlyIDFile)
  190. local magicNumber = GUIscale/4
  191. local cannonHitPosChannel = tonumber(config.cannonHitPosChannel)
  192. local controlChannel = tonumber(config.controlChannel)
  193.  
  194. if modem then
  195. modem.open(cannonHitPosChannel)
  196. modem.open(controlChannel)
  197. end
  198.  
  199. if mode == 1 then
  200. sourceX, sourceY, sourceZ = string.match(config.source, "(%-?%d+),(%-?%d+),(%-?%d+)")
  201. sourceX = tonumber(sourceX)
  202. sourceY = tonumber(sourceY)
  203. sourceZ = tonumber(sourceZ)
  204. else
  205. local pos = ship.getWorldspacePosition()
  206. sourceX, sourceY, sourceZ = pos.x, pos.y, pos.z
  207. end
  208.  
  209. print("Source X: " .. sourceX)
  210. print("Source Y: " .. sourceY)
  211. print("Source Z: " .. sourceZ)
  212. print("Resolution: " .. screenWidth .. ", " .. screenHeight)
  213. if screenWidth == 3440 and screenHeight == 1440 then widthMagic = 1.125 else widthMagic = 0.92 end
  214. holo.Resize(screenWidth/4,screenHeight/4)
  215. local screenSizeScale = 4
  216. holo.SetScale(0,0)
  217.  
  218. local function isFriendly(id)
  219. for _, friendlyID in ipairs(friendlyIDs) do
  220. if id == friendlyID then
  221. return true
  222. end
  223. end
  224. return false
  225. end
  226.  
  227. -- Function to project 3D coordinates to 2D screen coordinates
  228. local function projectToScreen(x, y, z, userPos, lookVector)
  229. local dx = x - userPos[1]
  230. local dy = -(y - userPos[2])
  231. local dz = z - userPos[3]
  232.  
  233. local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
  234. local playerYaw = math.deg(math.atan2(lz, lx))
  235. local playerPitch = math.deg(math.asin(-ly))
  236. playerYaw = playerYaw + 90
  237. if playerYaw < 0 then
  238. playerYaw = playerYaw + 360
  239. end
  240.  
  241. -- Calculate yaw difference
  242. local targetYaw = math.deg(math.atan2(dz, dx)) + 90
  243. if targetYaw < 0 then
  244. targetYaw = targetYaw + 360
  245. end
  246.  
  247. local yawDiff = targetYaw - playerYaw
  248. if yawDiff > 180 then
  249. yawDiff = yawDiff - 360
  250. elseif yawDiff < -180 then
  251. yawDiff = yawDiff + 360
  252. end
  253.  
  254. if math.abs(yawDiff) > 90 then
  255. return nil, nil
  256. end
  257.  
  258. -- Calculate pitch difference
  259. local distXY = math.sqrt(dx * dx + dz * dz)
  260. local targetPitch = math.deg(math.atan2(dy, distXY))
  261. local pitchDiff = targetPitch - playerPitch
  262.  
  263. local screenDepth = screenWidth / 2 * math.tan(math.rad(fov / 1.125 / 2))
  264. local verticalScreenDepth = screenHeight * math.tan(math.rad(fov / 2))
  265.  
  266. local projectedX, projectedY
  267.  
  268. if yawDiff > 0 then
  269. projectedX = screenWidth / 2 + screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  270. else
  271. projectedX = screenWidth / 2 - screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  272. end
  273.  
  274. if pitchDiff > 0 then
  275. projectedY = screenHeight / 2 + screenHeight * math.tan(math.rad(fov / 0.95 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  276. else
  277. projectedY = screenHeight / 2 - screenHeight * math.tan(math.rad(fov / 1.05 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  278. end
  279.  
  280. projectedX = math.floor(projectedX / magicNumber)
  281. projectedY = math.floor(projectedY / magicNumber) + 20
  282.  
  283. return projectedX, projectedY
  284. end
  285.  
  286. -- Function to display pitch and yaw of a cannon
  287. local function angleToScreen(pitch, yaw, userPos, lookVector)
  288. local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
  289. local playerYaw = math.deg(math.atan2(lz, lx))
  290. local playerPitch = math.deg(math.asin(-ly))
  291. playerYaw = playerYaw + 90
  292. if playerYaw < 0 then
  293. playerYaw = playerYaw + 360
  294. end
  295.  
  296. -- Calculate yaw difference
  297. local yawDiff = yaw - playerYaw
  298. if yawDiff > 180 then
  299. yawDiff = yawDiff - 360
  300. elseif yawDiff < -180 then
  301. yawDiff = yawDiff + 360
  302. end
  303.  
  304. if math.abs(yawDiff) > 90 then
  305. return nil, nil
  306. end
  307.  
  308. -- Calculate pitch difference
  309. local pitchDiff = -pitch + playerPitch
  310.  
  311. local screenDepth = screenWidth / 2 * math.tan(math.rad(fov / 1.125 / 2))
  312. local verticalScreenDepth = screenHeight * math.tan(math.rad(fov / 2))
  313.  
  314. local projectedX, projectedY
  315.  
  316. if yawDiff > 0 then
  317. projectedX = screenWidth / 2 + screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  318. else
  319. projectedX = screenWidth / 2 - screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  320. end
  321.  
  322. if pitchDiff > 0 then
  323. projectedY = screenHeight / 2 + screenHeight * math.tan(math.rad(fov / 0.95 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  324. else
  325. projectedY = screenHeight / 2 - screenHeight * math.tan(math.rad(fov / 1.05 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  326. end
  327.  
  328. projectedX = math.floor(projectedX / magicNumber)
  329. projectedY = math.floor(projectedY / magicNumber) + 20
  330.  
  331. return projectedX, projectedY
  332. end
  333.  
  334. local function mouseAim(userPos, lookVector)
  335. lookTarget = {}
  336.  
  337. local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
  338. local playerYaw = math.deg(math.atan2(lz, lx))
  339. local playerPitch = math.deg(math.asin(-ly)) - 25
  340. playerYaw = playerYaw + 90
  341. if playerYaw < 0 then
  342. playerYaw = playerYaw + 360
  343. end
  344.  
  345. local yawRad = math.rad(playerYaw)
  346. local pitchRad = math.rad(playerPitch)
  347.  
  348. local dx = projectionDistance * math.cos(pitchRad) * math.sin(yawRad)
  349. local dz = -projectionDistance * math.cos(pitchRad) * math.cos(yawRad)
  350. local dy = -projectionDistance * math.sin(pitchRad)
  351.  
  352. local targetX = userPos[1] + dx
  353. local targetY = userPos[2] + dy
  354. local targetZ = userPos[3] + dz
  355. lookTarget = { x = targetX, y = targetY, z = targetZ }
  356. return lookTarget
  357. end
  358.  
  359.  
  360. local function isWithinRenderDistance(projectedX, projectedY, centerX, centerY, maxdx, maxdy, maxd)
  361. local dx = projectedX - centerX / magicNumber
  362. local dy = projectedY - centerY / magicNumber
  363.  
  364. if dx < maxdx then
  365. if dy < maxdy then
  366. local distance = math.sqrt(dx * dx + dy * dy)
  367. if distance <= maxd then
  368. return true
  369. else
  370. return false
  371. end
  372. else
  373. return false
  374. end
  375. else
  376. return false
  377. end
  378. end
  379.  
  380. -- Function to check for overlap and adjust positions
  381. local function filterElements(elements)
  382. table.sort(elements, function(a, b) return a.mass > b.mass end) -- Sort by mass
  383. local filteredElements = {}
  384.  
  385. for i, element in ipairs(elements) do
  386. local overlap = false
  387. for _, filteredElement in ipairs(filteredElements) do
  388. local dx = math.abs(element.screenX - filteredElement.screenX)
  389. local dy = math.abs(element.screenY - filteredElement.screenY)
  390. if dx < 800 / GUIscale and dy < 800 / GUIscale then
  391. overlap = true
  392. element.renderInfo = false
  393. break
  394. end
  395. end
  396.  
  397. table.insert(filteredElements, element)
  398.  
  399. end
  400.  
  401. return filteredElements
  402. end
  403.  
  404. -- Function to render elements
  405. local function renderElements(elements, cannonHitPos, pInfo, lockedTarget)
  406. if not holo then return end -- Ensure hologram peripheral is available
  407.  
  408. -- Set the background to transparent
  409. holo.SetClearColor(0x00000000) -- Fully transparent (RGBA: 0,0,0,0)
  410.  
  411. local circleRadius = math.min(screenWidth, screenHeight) / 4
  412.  
  413. -- Iterate through detected objects and render them on the hologram
  414. for _, element in ipairs(elements) do
  415. local color = element.color
  416. if lockedTarget and element.id == lockedTarget.id then
  417. color = 0xFF0000FF -- Highlight locked target in red
  418. end
  419.  
  420. -- Map screen coordinates to hologram coordinates
  421. local holoX = math.floor(element.screenX / 4) -- Scale down for better fit
  422. local holoY = math.floor(element.screenY / 4) -- Adjust scaling as needed
  423.  
  424. -- Define the size of the box for the target
  425. local boxSize = 6 -- Increase the box size for better visibility
  426.  
  427. -- Ensure the coordinates fit within the hologram display bounds
  428. if holoX >= 0 and holoX < screenWidth / 4 and holoY >= 0 and holoY < screenHeight / 4 and element.renderBox then
  429. -- Draw a bounding box around the detected object
  430. holo.DrawLine(holoX - boxSize, holoY - boxSize, holoX + boxSize, holoY - boxSize, color, 1) -- Top
  431. holo.DrawLine(holoX - boxSize, holoY + boxSize, holoX + boxSize, holoY + boxSize, color, 1) -- Bottom
  432. holo.DrawLine(holoX - boxSize, holoY - boxSize, holoX - boxSize, holoY + boxSize, color, 1) -- Left
  433. holo.DrawLine(holoX + boxSize, holoY - boxSize, holoX + boxSize, holoY + boxSize, color, 1) -- Right
  434.  
  435. if element.renderInfo then
  436. -- Display object ID & distance on the hologram (smaller text)
  437. holo.Text(holoX + boxSize + 2, holoY - boxSize, tostring(element.id), color, 1) -- Target ID
  438. holo.Text(holoX + boxSize + 2, holoY + boxSize, tostring(element.distance) .. "m", color, 1) -- Distance
  439. holo.Text(holoX + boxSize + 2, holoY + boxSize * 3, tostring(element.speed) .. "m/s", color, 1) -- Speed
  440. end
  441. else
  442. -- Draw an edge indicator for objects outside the display bounds
  443. --drawEdgeIndicator(holo, element.screenX, element.screenY, screenWidth / 4, screenHeight / 4, circleRadius)
  444. end
  445. end
  446. end
  447.  
  448. local function lockHighestThreatTarget(elements, centerX, centerY, radius)
  449. local closestTarget = nil
  450. local closestDistance = math.huge -- Initialize to a large number
  451.  
  452. for _, element in ipairs(elements) do
  453. if element.id then
  454. local dx = element.screenX - centerX / magicNumber
  455. local dy = element.screenY - centerY / magicNumber
  456. local distance = math.sqrt(dx * dx + dy * dy)
  457.  
  458. -- Check if the target is within the locking radius on screen
  459. if distance <= radius / GUIscale then
  460. -- If this target is closer to the center than the current closest target, update
  461. if distance < closestDistance then
  462. closestTarget = element
  463. closestDistance = distance
  464. end
  465. end
  466. end
  467. end
  468.  
  469. return closestTarget
  470. end
  471.  
  472. local function modemMessage()
  473. while true do
  474. if modem then
  475. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  476. if channel == cannonHitPosChannel then
  477. cannonHitPos = message
  478. elseif channel == controlChannel then
  479. controls = message
  480. end
  481. else
  482. sleep()
  483. end
  484. end
  485. end
  486.  
  487. local function getAngularVelocity(currentYaw, currentTime)
  488. if lastYaw and lastYawTime then
  489. local deltaTime = currentTime - lastYawTime
  490. local deltaYaw = (currentYaw - lastYaw + math.pi) % (2 * math.pi) - math.pi
  491. return deltaYaw / deltaTime -- Radians per second
  492. end
  493. return 0
  494. end
  495.  
  496. local function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  497. local radians = math.rad(angle)
  498. local u = projectileSpeed/20
  499. local part1 = u * math.cos(radians) / math.log(cd)
  500. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  501. local XR = part1 * part2
  502.  
  503. return XR
  504. end
  505.  
  506. local function findBestPitch(targetX, targetY, targetZ, sourceX, sourceY, sourceZ, initialVelocity, g, cd, c_est, projectileSpeed)
  507. local bestLowPitch = nil
  508. local bestHighPitch = nil
  509. local bestLowDistance = math.huge
  510. local bestHighDistance = math.huge
  511. local targetDistance = math.sqrt((targetX - sourceX)^2 + (targetZ - sourceZ)^2)
  512.  
  513. for pitch = 0, 70, 0.05 do -- Iterate over pitch angles
  514. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est, projectileSpeed)
  515. local distanceDifference = math.abs(calculatedRange - targetDistance)
  516.  
  517. -- Find the low-angle solution
  518. if pitch <= 30 then
  519. if distanceDifference < bestLowDistance then
  520. bestLowDistance = distanceDifference
  521. bestLowPitch = pitch
  522. end
  523. -- Find the high-angle solution
  524. elseif pitch > 30 then
  525. if distanceDifference < bestHighDistance then
  526. bestHighDistance = distanceDifference
  527. bestHighPitch = pitch
  528. end
  529. end
  530. end
  531.  
  532. --prioritize the low-angle solution
  533. return bestLowPitch
  534. end
  535.  
  536. local function customProportional(error, Kp)
  537. -- Nonlinear proportional scaling
  538. -- Example: Quadratic growth for small errors
  539. local scaleFactor = 0.3 -- Controls how quickly the value grows for small errors
  540.  
  541. local absError = math.abs(error)
  542. local proportional = Kp * (absError / (1 + scaleFactor * absError)) -- Sigmoid-like growth
  543.  
  544. if error < 0 then
  545. proportional = -proportional -- Preserve the sign of the error
  546. end
  547.  
  548. return math.abs(proportional) * (error < 0 and -1 or 1) -- Cap the value
  549. end
  550.  
  551. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  552. -- Nonlinear proportional term using the custom function
  553. local proportional = customProportional(error, Kp)
  554.  
  555. -- Integral and derivative components
  556. integral = integral + error * dt
  557. local derivative = (error - prevError) / dt
  558.  
  559. -- Calculate the PID output
  560. local output = proportional + (Ki * integral) + (Kd * derivative)
  561.  
  562. -- Return the PID output, updated integral, and current error
  563. return output, integral, error
  564. end
  565.  
  566.  
  567. -- Yaw control function using PID
  568. local function yawControl(deltaYaw, currentYaw)
  569. if math.abs(deltaYaw) > 0.9 and math.abs(deltaYaw) < 1.2 then
  570. local yawSpeed, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, deltaYaw, yawIntegral, yawPrevError, dt)
  571.  
  572. if yawSpeed < 0 then
  573. yawSign = -1
  574. else
  575. yawSign = 1
  576. end
  577. yawSpeed = 1 * yawSign
  578.  
  579. if controls.accelerate or controls.decelerate then
  580. if controls.turnLeft then
  581. --turn level -1
  582. turnFactor = math.min(turnFactor + 4, 18)
  583. elseif controls.turnRight then
  584. --turn level 1
  585. turnFactor = math.max(turnFactor - 4, -18)
  586. else
  587. if turnFactor > 6 then
  588. turnFactor = turnFactor - 6
  589. elseif turnFactor < -6 then
  590. turnFactor = turnFactor + 6
  591. else
  592. turnFactor = 0
  593. end
  594. end
  595. else
  596. if controls.turnLeft then
  597. --turn level -2
  598. turnFactor = math.min(turnFactor + 2, 20)
  599. elseif controls.turnRight then
  600. --turn level 2
  601. turnFactor = math.max(turnFactor - 2, -20)
  602. else
  603. if turnFactor > 6 then
  604. turnFactor = turnFactor - 6
  605. elseif turnFactor < -6 then
  606. turnFactor = turnFactor + 6
  607. else
  608. turnFactor = 0
  609. end
  610. end
  611. end
  612.  
  613. if controls.decelerate then
  614. turnFactor = -turnFactor
  615. end
  616.  
  617. yawSpeed = yawSpeed + turnFactor
  618.  
  619.  
  620. --print("deltaYaw: " .. deltaYaw)
  621. --print("yawSpeed: " .. yawSpeed)
  622.  
  623. -- Set motor speed based on PID output
  624. yawMotor.setTargetSpeed(-yawSpeed)
  625. elseif math.abs(deltaYaw) > 0.9 then -- Only adjust if yaw error is significant
  626. -- PID controller for yaw
  627. local yawSpeed, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, deltaYaw, yawIntegral, yawPrevError, dt)
  628.  
  629. -- Constrain the yaw speed to prevent runaway spinning
  630. yawSpeed = math.max(-32, math.min(32, yawSpeed))
  631.  
  632. if controls.accelerate or controls.decelerate then
  633. if controls.turnLeft then
  634. --turn level -1
  635. turnFactor = math.min(turnFactor + 4, 18)
  636. elseif controls.turnRight then
  637. --turn level 1
  638. turnFactor = math.max(turnFactor - 4, -18)
  639. else
  640. if turnFactor > 6 then
  641. turnFactor = turnFactor - 6
  642. elseif turnFactor < -6 then
  643. turnFactor = turnFactor + 6
  644. else
  645. turnFactor = 0
  646. end
  647. end
  648. else
  649. if controls.turnLeft then
  650. --turn level -2
  651. turnFactor = math.min(turnFactor + 2, 20)
  652. elseif controls.turnRight then
  653. --turn level 2
  654. turnFactor = math.max(turnFactor - 2, -20)
  655. else
  656. if turnFactor > 6 then
  657. turnFactor = turnFactor - 6
  658. elseif turnFactor < -6 then
  659. turnFactor = turnFactor + 6
  660. else
  661. turnFactor = 0
  662. end
  663. end
  664. end
  665.  
  666. if controls.decelerate then
  667. turnFactor = -turnFactor
  668. end
  669.  
  670. yawSpeed = yawSpeed + turnFactor
  671.  
  672. print("deltaYaw: " .. deltaYaw)
  673. print("yawSpeed: " .. yawSpeed)
  674.  
  675. -- Set motor speed based on PID output
  676. yawMotor.setTargetSpeed(-yawSpeed)
  677.  
  678. else
  679. yawMotor.setTargetSpeed(0) -- Stop motor if error is too small
  680. end
  681. end
  682.  
  683. local function aimCannon(targetPos, targetVel, sourceX, sourceY, sourceZ, currentPitch, currentYaw)
  684. if sourceX and sourceY and sourceZ and currentPitch and currentYaw then
  685. local currentTime = os.clock()
  686. local dt = currentTime - lastTime
  687. if dt == 0 then return end -- Prevent division by zero
  688. lastTime = currentTime
  689.  
  690. local dx = targetPos.x - sourceX
  691. local dy = targetPos.y - sourceY
  692. local dz = targetPos.z - sourceZ
  693. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  694.  
  695. local shipVelocity = ship.getVelocity()
  696.  
  697. local estimateTime = distance / (projectileSpeed - 10) -- assuming velocity units and time units need adjustment
  698. local estimateX = targetPos.x + (targetVel.x - shipVelocity.x) * estimateTime
  699. local estimateY = targetPos.y + (targetVel.y - shipVelocity.y) * estimateTime
  700. local estimateZ = targetPos.z + (targetVel.z - shipVelocity.z) * estimateTime
  701.  
  702. local dx = estimateX - sourceX
  703. local dy = estimateY - sourceY
  704. local dz = estimateZ - sourceZ
  705.  
  706. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  707. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  708.  
  709. local yaw = math.deg(math.atan2(-dx, dz))
  710. yaw = (yaw + 180) % 360
  711.  
  712. -- Adjust pitch based on distance adjustments
  713.  
  714. pitch = pitch + findBestPitch(estimateX, estimateY, estimateZ, sourceX, sourceY, sourceZ, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  715.  
  716. local deltaYaw = (yaw - currentYaw + 180) % 360 - 180
  717. local deltaPitch = pitch - currentPitch
  718.  
  719. -- Turning and pitch adjustment logic
  720. parallel.waitForAll(
  721. function() yawControl(deltaYaw, currentYaw) end,
  722. function()
  723. modem.transmit(cannonHitPosChannel,0,{pitch = pitch, yaw = yaw})
  724. print("transmiting "..pitch.." at channel "..cannonHitPosChannel)
  725. end
  726. )
  727.  
  728. lastCurrentYaw = currentYaw
  729. lastCurrentPitch = currentPitch
  730. end
  731. end
  732.  
  733. local function targetLockAndAim()
  734. while true do
  735. currentPitch,currentYaw = cannonHitPos[6],cannonHitPos[7]
  736. source = cannonHitPos[5]
  737. if controls.cannonControlMode == "mouseAim" then
  738. currentPitch, currentYaw = cannonHitPos[6], cannonHitPos[7]
  739. source = cannonHitPos[5]
  740.  
  741.  
  742. if pInfo.nickname then
  743. lockedTarget = lockHighestThreatTarget(elements, screenWidth / 2, screenHeight / 2, 1000)
  744. if lockedTarget then
  745. lockedTargetScan = radar.scanForShips(5000)
  746. for _, object in ipairs(lockedTargetScan) do
  747. if object.id == lockedTarget.id then
  748. -- Update the locked target information
  749. lockedTarget.pos = object.pos
  750. lockedTarget.velocity = object.velocity
  751. break
  752. end
  753. end
  754. if lockedTarget.pos then
  755. aimCannon(lockedTarget.pos, lockedTarget.velocity, source.x, source.y, source.z, currentPitch, currentYaw)
  756. end
  757. else
  758. lookTarget = mouseAim(pInfo.pos, pInfo.lookVector)
  759. if lookTarget then
  760. --[[local shipVelocity = ship.getVelocity()
  761. source.x = source.x + shipVelocity.x * 0.1
  762. source.y = source.y + shipVelocity.y * 0.1
  763. source.z = source.z + shipVelocity.z * 0.1]]
  764. aimCannon(lookTarget, {x=0, y=0, z=0}, source.x, source.y, source.z, currentPitch, currentYaw)
  765. end
  766. end
  767. end
  768. else
  769.  
  770. end
  771. sleep()
  772. end
  773. end
  774.  
  775. local function manualCannonControl()
  776. while true do
  777. if controls.cannonControlMode == "manual" then
  778. if controls then
  779. -- Control yaw and pitch manually with arrow keys
  780. print("cannon current pitch"..cannonHitPos[6])
  781. if controls.cannonUp then
  782. -- Increase pitch
  783. modem.transmit(cannonHitPosChannel,0,{pitch = cannonHitPos[6] + 1.5, yaw = currentYaw})
  784. elseif controls.cannonDown then
  785. -- Decrease pitch
  786. modem.transmit(cannonHitPosChannel,0,{pitch = cannonHitPos[6] - 1.5, yaw = currentYaw})
  787. else
  788.  
  789. end
  790. if controls.cannonLeft then
  791. -- Turn left
  792. yawMotor.setTargetSpeed(8)
  793. elseif controls.cannonRight then
  794. -- Turn right
  795. yawMotor.setTargetSpeed(-8)
  796. else
  797. yawMotor.setTargetSpeed(0)
  798. end
  799. else
  800. yawMotor.setTargetSpeed(0)
  801. end
  802. sleep()
  803. else
  804. sleep() -- Sleep for a short time if not in manual mode
  805. end
  806. end
  807. end
  808.  
  809. -- Update the main function to remove target locking and aiming
  810. local function main()
  811. while true do
  812. holo.Clear()
  813. local playerList = radar.scanForPlayers(1000)
  814.  
  815. for _, player in ipairs(playerList) do
  816. local playerName = player.nickname
  817. local playerPosition = player.pos
  818. local lookAngle = player.look_angle
  819.  
  820. if player.nickname == userID then
  821. pInfo = {
  822. nickname = player.nickname,
  823. pos = player.pos,
  824. lookVector = lookAngle
  825. }
  826. end
  827. end
  828.  
  829. if pInfo.nickname then
  830. local objectList = radar.scanForShips(10000)
  831. --ar.clear()
  832.  
  833. elements = {}
  834. for _, object in ipairs(objectList) do
  835. local objX, objY, objZ = object.pos.x, object.pos.y, object.pos.z
  836. local screenX, screenY = projectToScreen(objX, objY, objZ, pInfo.pos, pInfo.lookVector)
  837. local distance = math.floor(math.sqrt((object.pos.x - pInfo.pos[1]) ^ 2 + (object.pos.y - pInfo.pos[2]) ^ 2 + (object.pos.z - pInfo.pos[3]) ^ 2))
  838. local speed = math.floor(math.sqrt(object.velocity.x ^ 2 + object.velocity.y ^ 2 + object.velocity.z ^ 2))
  839. local color
  840. if isFriendly(object.name) then
  841. color = 0x009cff88 -- Friendly, blue color
  842. elseif object.mass < 8000 then
  843. color = 0x99999988 -- type unknown/low threat
  844. elseif object.mass < 30000 then
  845. if speed > 40 then
  846. -- high speed low mass, potential missile
  847.  
  848. local missileVector = {object.velocity.x, object.velocity.y, object.velocity.z}
  849. local toPlayerVector = {pInfo.pos[1] - objX, pInfo.pos[2] - objY, pInfo.pos[3] - objZ}
  850. local dotProduct = missileVector[1] * toPlayerVector[1] + missileVector[2] * toPlayerVector[2] + missileVector[3] * toPlayerVector[3]
  851. if dotProduct > 0 then
  852. color = 0xff5600ff -- missile coming, high threat
  853. else
  854. color = 0xFFFF00ff -- potential threat
  855. end
  856. else
  857. color = 0x00FF0088 -- low mass low speed, low threat
  858. end
  859. elseif object.mass < 200000 then
  860. if speed > 20 then
  861. color = 0xFFFF00ff -- jet
  862. else
  863. color = 0xfff70088 -- Medium sized vehicle, tanks, helicopter
  864. end
  865. else
  866. color = 0xffc300ff -- Large sized vehicle, ships, strategic bomber
  867. end
  868.  
  869. if distance > 20 then
  870. if screenX and screenY then
  871. table.insert(elements, {
  872. id = object.id,
  873. screenX = screenX,
  874. screenY = screenY,
  875. frameSize = 20,
  876. color = color,
  877. distance = distance,
  878. mass = object.mass,
  879. speed = speed,
  880. velocity = object.velocity,
  881. renderInfo = true,
  882. renderBox = isWithinRenderDistance(screenX, screenY, screenWidth / 2, screenHeight / 2, 4000 / GUIscale, 4800 / GUIscale, 3200 / GUIscale)
  883. })
  884. end
  885. end
  886. end
  887.  
  888. local filteredElements = filterElements(elements)
  889.  
  890. for _, element in ipairs(elements) do
  891. local found = false
  892. for _, filteredElement in ipairs(filteredElements) do
  893. if element.id == filteredElement.id then
  894. found = true
  895. break
  896. end
  897. end
  898. if not found then
  899. element.renderInfo = false
  900. end
  901. end
  902. renderElements(filteredElements, cannonHitPos, pInfo, lockedTarget)
  903. end
  904.  
  905. if pInfo then
  906. local AimTarget = mouseAim(pInfo.pos, pInfo.lookVector)
  907. local screenX, screenY = projectToScreen(AimTarget.x, AimTarget.y, AimTarget.z, pInfo.pos, pInfo.lookVector)
  908. if screenX and screenY then
  909. --ar.drawStringWithId("AimCrossHair","X", screenX+20, screenY+80, 0xFFFFFF)
  910. end
  911. end
  912.  
  913. if ship.getVelocity() then
  914. local velocity = ship.getVelocity()
  915. local speed = math.floor(math.sqrt(velocity.x^2 + velocity.y^2 + velocity.z^2))
  916.  
  917. --ar.drawStringWithId("AimCrossHair","speed: "..speed, 100, 500, 0xFFFFFF)
  918. end
  919. holo.Flush()
  920. sleep()
  921. end
  922. end
  923.  
  924. local function hitMark()
  925. while true do
  926. if cannonHitPos and modem then
  927. local playerList = radar.scanForPlayers(1000)
  928. for _, player in ipairs(playerList) do
  929. local playerName = player.nickname
  930. local playerPosition = player.pos
  931. local lookAngle = player.look_angle
  932.  
  933. if player.nickname == userID then
  934. pInfo = {
  935. nickname = player.nickname,
  936. pos = player.pos,
  937. lookVector = lookAngle
  938. }
  939. end
  940. end
  941.  
  942. if cannonHitPos[4] == "coordinate" then
  943. if cannonHitPos then
  944. objX, objY, objZ = cannonHitPos[1], cannonHitPos[2], cannonHitPos[3]
  945. end
  946. if objX and objY and objZ then
  947. local screenX, screenY = projectToScreen(objX, objY, objZ, pInfo.pos, pInfo.lookVector)
  948. if screenX and screenY then
  949. --ar.clearElement("CrossHair")
  950. --ar.drawStringWithId("CrossHair","X", screenX, screenY, 0xFF0000)
  951. end
  952. end
  953. elseif cannonHitPos[3] == "degree" then
  954. print("pitch: "..cannonHitPos[1])
  955. print("yaw: "..cannonHitPos[2])
  956. local screenX, screenY = angleToScreen(cannonHitPos[1], cannonHitPos[2], pInfo.pos, pInfo.lookVector)
  957. if screenX and screenY then
  958. --ar.clearElement("CrossHair")
  959. --ar.drawStringWithId("CrossHair","X", screenX, screenY, 0xFF0000)
  960. end
  961. end
  962. end
  963. sleep()
  964. end
  965. end
  966.  
  967. -- Main loop
  968. parallel.waitForAny(
  969. modemMessage,
  970. main,
  971. hitMark,
  972. targetLockAndAim,
  973. manualCannonControl
  974. )
  975.  
Advertisement
Add Comment
Please, Sign In to add comment