MegiRicky

BradleyAim

Oct 17th, 2024 (edited)
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.78 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 = 240
  40. local g = 0.025
  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.8
  57. local Ki_yaw = 0
  58. local Kd_yaw = 0.015
  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 + 5, 42)
  583. elseif controls.turnRight then
  584. --turn level 1
  585. turnFactor = math.max(turnFactor - 5, -42)
  586. else
  587. if turnFactor > 3 then
  588. turnFactor = turnFactor - 3
  589. elseif turnFactor < -3 then
  590. turnFactor = turnFactor + 3
  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 + 13, 26)
  599. elseif controls.turnRight then
  600. --turn level 2
  601. turnFactor = math.max(turnFactor - 13, -26)
  602. else
  603. if turnFactor > 8 then
  604. turnFactor = turnFactor - 8
  605. elseif turnFactor < -8 then
  606. turnFactor = turnFactor + 8
  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. --print("deltaYaw: " .. deltaYaw)
  620. --print("yawSpeed: " .. yawSpeed)
  621.  
  622. -- Set motor speed based on PID output
  623. yawMotor.setTargetSpeed(-yawSpeed)
  624. elseif math.abs(deltaYaw) > 0.9 then -- Only adjust if yaw error is significant
  625. -- PID controller for yaw
  626. local yawSpeed, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, deltaYaw, yawIntegral, yawPrevError, dt)
  627.  
  628. -- Constrain the yaw speed to prevent runaway spinning
  629. yawSpeed = math.max(-32, math.min(32, yawSpeed))
  630.  
  631. if controls.accelerate or controls.decelerate then
  632. if controls.turnLeft then
  633. --turn level -1
  634. turnFactor = math.min(turnFactor + 5, 28)
  635. elseif controls.turnRight then
  636. --turn level 1
  637. turnFactor = math.max(turnFactor - 5, -28)
  638. else
  639. if turnFactor > 3 then
  640. turnFactor = turnFactor - 3
  641. elseif turnFactor < -3 then
  642. turnFactor = turnFactor + 3
  643. else
  644. turnFactor = 0
  645. end
  646. end
  647. else
  648. if controls.turnLeft then
  649. --turn level -2
  650. turnFactor = math.min(turnFactor + 13, 26)
  651. elseif controls.turnRight then
  652. --turn level 2
  653. turnFactor = math.max(turnFactor - 13, -26)
  654. else
  655. if turnFactor > 8 then
  656. turnFactor = turnFactor - 8
  657. elseif turnFactor < -8 then
  658. turnFactor = turnFactor + 8
  659. else
  660. turnFactor = 0
  661. end
  662. end
  663. end
  664.  
  665. if controls.decelerate then
  666. turnFactor = -turnFactor
  667. end
  668.  
  669. yawSpeed = yawSpeed + turnFactor
  670.  
  671. print("deltaYaw: " .. deltaYaw)
  672. print("yawSpeed: " .. yawSpeed)
  673.  
  674. -- Set motor speed based on PID output
  675. yawMotor.setTargetSpeed(-yawSpeed)
  676.  
  677. else
  678. yawMotor.setTargetSpeed(0) -- Stop motor if error is too small
  679. end
  680. end
  681.  
  682. local function aimCannon(targetPos, targetVel, sourceX, sourceY, sourceZ, currentPitch, currentYaw)
  683. if sourceX and sourceY and sourceZ and currentPitch and currentYaw then
  684. local currentTime = os.clock()
  685. local dt = currentTime - lastTime
  686. if dt == 0 then return end -- Prevent division by zero
  687. lastTime = currentTime
  688.  
  689. local dx = targetPos.x - sourceX
  690. local dy = targetPos.y - sourceY
  691. local dz = targetPos.z - sourceZ
  692. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  693.  
  694. local shipVelocity = ship.getVelocity()
  695.  
  696. local estimateTime = distance / (projectileSpeed - 10) -- assuming velocity units and time units need adjustment
  697. local estimateX = targetPos.x + (targetVel.x - shipVelocity.x) * estimateTime
  698. local estimateY = targetPos.y + (targetVel.y - shipVelocity.y) * estimateTime
  699. local estimateZ = targetPos.z + (targetVel.z - shipVelocity.z) * estimateTime
  700.  
  701. local dx = estimateX - sourceX
  702. local dy = estimateY - sourceY
  703. local dz = estimateZ - sourceZ
  704.  
  705. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  706. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  707.  
  708. local yaw = math.deg(math.atan2(-dx, dz))
  709. yaw = (yaw + 180) % 360
  710.  
  711. -- Adjust pitch based on distance adjustments
  712.  
  713. pitch = pitch + findBestPitch(estimateX, estimateY, estimateZ, sourceX, sourceY, sourceZ, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  714.  
  715. local deltaYaw = (yaw - currentYaw + 180) % 360 - 180
  716. local deltaPitch = pitch - currentPitch
  717.  
  718. -- Turning and pitch adjustment logic
  719. parallel.waitForAll(
  720. function() yawControl(deltaYaw, currentYaw) end,
  721. function()
  722. modem.transmit(cannonHitPosChannel,0,{pitch = pitch, yaw = yaw})
  723. print("transmiting "..pitch.." at channel "..cannonHitPosChannel)
  724. end
  725. )
  726.  
  727. lastCurrentYaw = currentYaw
  728. lastCurrentPitch = currentPitch
  729. end
  730. end
  731.  
  732. local function targetLockAndAim()
  733. while true do
  734. currentPitch,currentYaw = cannonHitPos[6],cannonHitPos[7]
  735. source = cannonHitPos[5]
  736. if controls.cannonControlMode == "mouseAim" then
  737. currentPitch, currentYaw = cannonHitPos[6], cannonHitPos[7]
  738. source = cannonHitPos[5]
  739.  
  740.  
  741. if pInfo.nickname then
  742. lockedTarget = lockHighestThreatTarget(elements, screenWidth / 2, screenHeight / 2, 1000)
  743. if lockedTarget then
  744. lockedTargetScan = radar.scanForShips(5000)
  745. for _, object in ipairs(lockedTargetScan) do
  746. if object.id == lockedTarget.id then
  747. -- Update the locked target information
  748. lockedTarget.pos = object.pos
  749. lockedTarget.velocity = object.velocity
  750. break
  751. end
  752. end
  753. if lockedTarget.pos then
  754. aimCannon(lockedTarget.pos, lockedTarget.velocity, source.x, source.y, source.z, currentPitch, currentYaw)
  755. end
  756. else
  757. lookTarget = mouseAim(pInfo.pos, pInfo.lookVector)
  758. if lookTarget then
  759. --[[local shipVelocity = ship.getVelocity()
  760. source.x = source.x + shipVelocity.x * 0.1
  761. source.y = source.y + shipVelocity.y * 0.1
  762. source.z = source.z + shipVelocity.z * 0.1]]
  763. aimCannon(lookTarget, {x=0, y=0, z=0}, source.x, source.y, source.z, currentPitch, currentYaw)
  764. end
  765. end
  766. end
  767. else
  768.  
  769. end
  770. sleep()
  771. end
  772. end
  773.  
  774. local function manualCannonControl()
  775. while true do
  776. if controls.cannonControlMode == "manual" then
  777. if controls then
  778. -- Control yaw and pitch manually with arrow keys
  779. print("cannon current pitch"..cannonHitPos[6])
  780. if controls.cannonUp then
  781. -- Increase pitch
  782. modem.transmit(cannonHitPosChannel,0,{pitch = cannonHitPos[6] + 1.5, yaw = currentYaw})
  783. elseif controls.cannonDown then
  784. -- Decrease pitch
  785. modem.transmit(cannonHitPosChannel,0,{pitch = cannonHitPos[6] - 1.5, yaw = currentYaw})
  786. else
  787.  
  788. end
  789. if controls.cannonLeft then
  790. -- Turn left
  791. yawMotor.setTargetSpeed(8)
  792. elseif controls.cannonRight then
  793. -- Turn right
  794. yawMotor.setTargetSpeed(-8)
  795. else
  796. yawMotor.setTargetSpeed(0)
  797. end
  798. else
  799. yawMotor.setTargetSpeed(0)
  800. end
  801. sleep()
  802. else
  803. sleep() -- Sleep for a short time if not in manual mode
  804. end
  805. end
  806. end
  807.  
  808. -- Update the main function to remove target locking and aiming
  809. local function main()
  810. while true do
  811. holo.Clear()
  812. local playerList = radar.scanForPlayers(1000)
  813.  
  814. for _, player in ipairs(playerList) do
  815. local playerName = player.nickname
  816. local playerPosition = player.pos
  817. local lookAngle = player.look_angle
  818.  
  819. if player.nickname == userID then
  820. pInfo = {
  821. nickname = player.nickname,
  822. pos = player.pos,
  823. lookVector = lookAngle
  824. }
  825. end
  826. end
  827.  
  828. if pInfo.nickname then
  829. local objectList = radar.scanForShips(10000)
  830. --ar.clear()
  831.  
  832. elements = {}
  833. for _, object in ipairs(objectList) do
  834. local objX, objY, objZ = object.pos.x, object.pos.y, object.pos.z
  835. local screenX, screenY = projectToScreen(objX, objY, objZ, pInfo.pos, pInfo.lookVector)
  836. 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))
  837. local speed = math.floor(math.sqrt(object.velocity.x ^ 2 + object.velocity.y ^ 2 + object.velocity.z ^ 2))
  838. local color
  839. if isFriendly(object.name) then
  840. color = 0x009cff88 -- Friendly, blue color
  841. elseif object.mass < 8000 then
  842. color = 0x99999988 -- type unknown/low threat
  843. elseif object.mass < 30000 then
  844. if speed > 40 then
  845. -- high speed low mass, potential missile
  846.  
  847. local missileVector = {object.velocity.x, object.velocity.y, object.velocity.z}
  848. local toPlayerVector = {pInfo.pos[1] - objX, pInfo.pos[2] - objY, pInfo.pos[3] - objZ}
  849. local dotProduct = missileVector[1] * toPlayerVector[1] + missileVector[2] * toPlayerVector[2] + missileVector[3] * toPlayerVector[3]
  850. if dotProduct > 0 then
  851. color = 0xff5600ff -- missile coming, high threat
  852. else
  853. color = 0xFFFF00ff -- potential threat
  854. end
  855. else
  856. color = 0x00FF0088 -- low mass low speed, low threat
  857. end
  858. elseif object.mass < 200000 then
  859. if speed > 20 then
  860. color = 0xFFFF00ff -- jet
  861. else
  862. color = 0xfff70088 -- Medium sized vehicle, tanks, helicopter
  863. end
  864. else
  865. color = 0xffc300ff -- Large sized vehicle, ships, strategic bomber
  866. end
  867.  
  868. if distance > 20 then
  869. if screenX and screenY then
  870. table.insert(elements, {
  871. id = object.id,
  872. screenX = screenX,
  873. screenY = screenY,
  874. frameSize = 20,
  875. color = color,
  876. distance = distance,
  877. mass = object.mass,
  878. speed = speed,
  879. velocity = object.velocity,
  880. renderInfo = true,
  881. renderBox = isWithinRenderDistance(screenX, screenY, screenWidth / 2, screenHeight / 2, 4000 / GUIscale, 4800 / GUIscale, 3200 / GUIscale)
  882. })
  883. end
  884. end
  885. end
  886.  
  887. local filteredElements = filterElements(elements)
  888.  
  889. for _, element in ipairs(elements) do
  890. local found = false
  891. for _, filteredElement in ipairs(filteredElements) do
  892. if element.id == filteredElement.id then
  893. found = true
  894. break
  895. end
  896. end
  897. if not found then
  898. element.renderInfo = false
  899. end
  900. end
  901. renderElements(filteredElements, cannonHitPos, pInfo, lockedTarget)
  902. end
  903.  
  904. if pInfo then
  905. local AimTarget = mouseAim(pInfo.pos, pInfo.lookVector)
  906. local screenX, screenY = projectToScreen(AimTarget.x, AimTarget.y, AimTarget.z, pInfo.pos, pInfo.lookVector)
  907. if screenX and screenY then
  908. --ar.drawStringWithId("AimCrossHair","X", screenX+20, screenY+80, 0xFFFFFF)
  909. end
  910. end
  911.  
  912. if ship.getVelocity() then
  913. local velocity = ship.getVelocity()
  914. local speed = math.floor(math.sqrt(velocity.x^2 + velocity.y^2 + velocity.z^2))
  915.  
  916. --ar.drawStringWithId("AimCrossHair","speed: "..speed, 100, 500, 0xFFFFFF)
  917. end
  918. holo.Flush()
  919. sleep()
  920. end
  921. end
  922.  
  923. local function hitMark()
  924. while true do
  925. if cannonHitPos and modem then
  926. local playerList = radar.scanForPlayers(1000)
  927. for _, player in ipairs(playerList) do
  928. local playerName = player.nickname
  929. local playerPosition = player.pos
  930. local lookAngle = player.look_angle
  931.  
  932. if player.nickname == userID then
  933. pInfo = {
  934. nickname = player.nickname,
  935. pos = player.pos,
  936. lookVector = lookAngle
  937. }
  938. end
  939. end
  940.  
  941. if cannonHitPos[4] == "coordinate" then
  942. if cannonHitPos then
  943. objX, objY, objZ = cannonHitPos[1], cannonHitPos[2], cannonHitPos[3]
  944. end
  945. if objX and objY and objZ then
  946. local screenX, screenY = projectToScreen(objX, objY, objZ, pInfo.pos, pInfo.lookVector)
  947. if screenX and screenY then
  948. --ar.clearElement("CrossHair")
  949. --ar.drawStringWithId("CrossHair","X", screenX, screenY, 0xFF0000)
  950. end
  951. end
  952. elseif cannonHitPos[3] == "degree" then
  953. print("pitch: "..cannonHitPos[1])
  954. print("yaw: "..cannonHitPos[2])
  955. local screenX, screenY = angleToScreen(cannonHitPos[1], cannonHitPos[2], pInfo.pos, pInfo.lookVector)
  956. if screenX and screenY then
  957. --ar.clearElement("CrossHair")
  958. --ar.drawStringWithId("CrossHair","X", screenX, screenY, 0xFF0000)
  959. end
  960. end
  961. end
  962. sleep()
  963. end
  964. end
  965.  
  966. -- Main loop
  967. parallel.waitForAny(
  968. modemMessage,
  969. main,
  970. hitMark,
  971. targetLockAndAim,
  972. manualCannonControl
  973. )
  974.  
Advertisement
Add Comment
Please, Sign In to add comment