MegiRicky

TuoChiangClassTurretNGDWEVR

Jul 26th, 2025
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 49.05 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 holo = peripheral.find("hologram")
  6.  
  7. local k = 1
  8. local nilCount = 0
  9. local i = 0
  10. local cannons = {}
  11. while nilCount < 200 do
  12. local cannon = peripheral.wrap("createbigcannons:cannon_mount_"..tostring(i))
  13. if not(cannon) then
  14. cannon = peripheral.wrap("cbcmodernwarfare:compact_mount_"..tostring(i))
  15. end
  16. if cannon then
  17. cannons[k] = cannon
  18. k = k + 1
  19. nilCount = 0
  20. print("found cannon")
  21. else
  22. nilCount = nilCount + 1
  23. end
  24. i = i + 1
  25. end
  26. print("Found "..#cannons.." cannons")
  27. for index, cannon in pairs(cannons) do
  28. if cannon then
  29. if cannon.assemble then
  30. cannon.assemble() -- Call assemble function
  31. print("Cannon at index " .. index .. " assembled.")
  32. else
  33. print("Cannon at index " .. index .. " has no assemble function.")
  34. end
  35. else
  36. break
  37. end
  38. end
  39.  
  40. redstone.setOutput("top",false)
  41.  
  42. local function askUser(prompt, defaultValue)
  43. print(prompt .. " (default: " .. defaultValue .. ")")
  44. local input = io.read()
  45. if input == "" then
  46. return defaultValue
  47. else
  48. return input
  49. end
  50. end
  51.  
  52. local cannonControlMode = "mouseAim"
  53.  
  54. local screenWidth, screenHeight, fov, GUIscale
  55. local sourceX, sourceY, sourceZ = 0,0,0
  56. local source = {}
  57. local userID
  58. local friendlyIDs
  59. local friendlyIDFile = "friendly_ids.txt"
  60. local widthMagic = 1.125
  61. local projectionDistance = 30
  62. local currentPitch, currentYaw = 0,0
  63. local lastCurrentPitch, lastCurrentYaw = 0,0
  64. local lockedTarget = nil
  65. local elements = {}
  66. local pInfo = {}
  67. local cannonHitPos = {}
  68. local pitchAdjustments = "1"
  69. local lastYawUpdateTime = 0
  70. local lastPitchUpdateTime = 0
  71. local updateInterval = 0.01
  72. local projectileSpeed = 250
  73. local g = 0.04
  74. local cd = 0.99
  75. local vm
  76.  
  77. local yawErrorSum = 0
  78. local lastYawError = 0
  79. local pitchErrorSum = 0
  80. local lastPitchError = 0
  81. local yawError = 0
  82. local yawIntegral = 0
  83. local yawPrevError = 0
  84. local pitchError = 0
  85. local pitchIntegral = 0
  86. local pitchPrevError = 0
  87. local lastTime = os.clock()
  88.  
  89. local Kp_yaw = 0.42
  90. local Ki_yaw = 0
  91. local Kd_yaw = 0.01
  92. local Kp_pitch = 0.035
  93. local Ki_pitch = 0.01
  94. local Kd_pitch = 0.035
  95. local dt = 0.1
  96.  
  97. local turnFactor = 0
  98.  
  99. local requiredRelativePitch,requiredRelativeYaw = 0,0
  100.  
  101. local controls = {cannonControlMode = "mouseAim"}
  102.  
  103. -- Configuration file paths
  104. local function readConfig(filename)
  105. if not fs.exists(filename) then
  106. print("Configuration file '" .. filename .. "' does not exist. Creating it.")
  107. file = fs.open(filename, "w")
  108.  
  109. resolution = askUser("Input your resolution eg.(1920,1080)", "3440,1440")
  110. file.writeLine("resolution=" .. resolution)
  111.  
  112. fov = askUser("Input your FOV eg.(70)", "70")
  113. file.writeLine("fov=" .. fov)
  114.  
  115. userID = askUser("Input your ID", "MegiRicky")
  116. file.writeLine("userID=" .. userID)
  117.  
  118. -- Integrating channel number into the config
  119. SPAAControlChannel = askUser("Input the SPAAControlChannel", "2100")
  120. file.writeLine("SPAAControlChannel=" .. SPAAControlChannel)
  121.  
  122. pitchCompensation = askUser("Input the pitchCompensation.(for when the plane and the computer is not on the same ship)","48.24")
  123. file.writeLine("pitchCompensation="..pitchCompensation)
  124.  
  125. file.close()
  126. end
  127. sleep(0.2)
  128. local file = fs.open(filename, "r")
  129. local config = {}
  130. local line = file.readLine()
  131. while line do
  132. local key, value = line:match("^(%w+)=(.*)$")
  133. config[key] = value
  134. line = file.readLine()
  135. end
  136. file.close()
  137. return config
  138. end
  139.  
  140. -- Function to edit configuration
  141. local function editConfig(filename)
  142. print("Do you want to edit the config? (yes/no),press enter to skip")
  143. local editChoice = io.read()
  144. if editChoice == "" then
  145. editChoice = "no"
  146. end
  147. if editChoice:lower() == "yes" then
  148. if fs.exists(filename) then
  149. fs.delete(filename)
  150. end
  151. return readConfig(filename)
  152. else
  153. return nil
  154. end
  155. end
  156.  
  157. -- Function to select or create config
  158. local function loadOrCreateConfig()
  159. print("Which player's config do you want to load?")
  160. local selectedID = io.read()
  161.  
  162. local configFile = selectedID .. "config.txt"
  163.  
  164. if fs.exists(configFile) then
  165. print("Config file for " .. selectedID .. " exists. Loading it.")
  166. local config = readConfig(configFile)
  167.  
  168. -- Ask if user wants to edit config
  169. editConfig(configFile)
  170.  
  171. return config
  172. else
  173. print("No config file found for " .. selectedID .. ". Creating a new one.")
  174. return readConfig(configFile)
  175. end
  176. end
  177.  
  178. -- Function to read friendly IDs from a file
  179. local function readFriendlyIDs(filename)
  180. if not fs.exists(filename) then
  181. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  182. local file = fs.open(filename, "w")
  183. print("Input friendly IDs separated by commas:")
  184. local ids = io.read()
  185. file.write(ids)
  186. file.close()
  187. end
  188.  
  189. local file = fs.open(filename, "r")
  190. local friendlyIDs = {}
  191. if file then
  192. local line = file.readLine()
  193. while line do
  194. for id in string.gmatch(line, "%d+") do
  195. table.insert(friendlyIDs, tonumber(id))
  196. end
  197. line = file.readLine()
  198. end
  199. file.close()
  200. end
  201. return friendlyIDs
  202. end
  203.  
  204. local function sign(x)
  205. return x > 0 and 1 or x < 0 and -1 or 0
  206. end
  207.  
  208. -- Load configuration
  209.  
  210. local config = loadOrCreateConfig()
  211. sleep(0.2)
  212. print(textutils.serialize(config))
  213. screenWidth, screenHeight = config.resolution:match("(%d+),(%d+)")
  214. screenWidth = tonumber(screenWidth)
  215. screenHeight = tonumber(screenHeight)
  216. fov = tonumber(config.fov)
  217. GUIscale = 4
  218. local mode = tonumber(config.mode)
  219. userID = config.userID
  220. friendlyIDs = readFriendlyIDs(friendlyIDFile)
  221. local magicNumber = GUIscale/4
  222. local SPAAControlChannel = tonumber(config.SPAAControlChannel)
  223. local cannonHitPosChannel = SPAAControlChannel + 10
  224.  
  225. local velocityFactor = tonumber(askUser("Input the velocity factor","1"))
  226.  
  227. if modem then
  228. modem.open(cannonHitPosChannel)
  229. modem.open(SPAAControlChannel)
  230. end
  231.  
  232. if mode == 1 then
  233. sourceX, sourceY, sourceZ = string.match(config.source, "(%-?%d+),(%-?%d+),(%-?%d+)")
  234. sourceX = tonumber(sourceX)
  235. sourceY = tonumber(sourceY)
  236. sourceZ = tonumber(sourceZ)
  237. else
  238. local pos = ship.getWorldspacePosition()
  239. sourceX, sourceY, sourceZ = pos.x, pos.y, pos.z
  240. end
  241.  
  242. print("Source X: " .. sourceX)
  243. print("Source Y: " .. sourceY)
  244. print("Source Z: " .. sourceZ)
  245. print("Resolution: " .. screenWidth .. ", " .. screenHeight)
  246. if screenWidth == 3440 and screenHeight == 1440 then widthMagic = 1.125 else widthMagic = 0.92 end
  247. holo.Resize(screenWidth/4,screenHeight/4)
  248. local screenSizeScale = 4
  249. holo.SetScale(0,0)
  250.  
  251. local function isFriendly(id)
  252. for _, friendlyID in ipairs(friendlyIDs) do
  253. if id == friendlyID then
  254. return true
  255. end
  256. end
  257. return false
  258. end
  259.  
  260. -- Normalize a vector
  261. local function normalizeVector(v)
  262. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  263. if length == 0 then
  264. return {0, 0, 0}
  265. end
  266. return {v[1] / length, v[2] / length, v[3] / length}
  267. end
  268.  
  269. -- Normalize the rotation matrix
  270. local function normalizeRotationMatrix(rotMatrix)
  271. local normalizedMatrix = {}
  272. for i = 1, #rotMatrix do
  273. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  274. end
  275. return normalizedMatrix
  276. end
  277.  
  278. -- Get the pitch of the ship
  279. local function getPitch()
  280. local rotMatrix = ship.getTransformationMatrix()
  281. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  282. return -math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  283. end
  284. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  285. -- Get the yaw of the ship
  286. local function getYaw()
  287. local rotMatrix = ship.getTransformationMatrix()
  288. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  289. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  290. end
  291.  
  292. -- Get the roll of the ship
  293. local function getRoll()
  294. local rotMatrix = ship.getTransformationMatrix()
  295. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  296. return -math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  297. end
  298.  
  299. -- Function to project 3D coordinates to 2D screen coordinates
  300. local function projectToScreen(x, y, z, userPos, lookVector)
  301. local dx = x - userPos[1]
  302. local dy = -(y - userPos[2])
  303. local dz = z - userPos[3]
  304.  
  305. local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
  306. local playerYaw = math.deg(math.atan2(lz, lx))
  307. local playerPitch = math.deg(math.asin(-ly))
  308. playerYaw = playerYaw + 90
  309. if playerYaw < 0 then
  310. playerYaw = playerYaw + 360
  311. end
  312.  
  313. -- Calculate yaw difference
  314. local targetYaw = math.deg(math.atan2(dz, dx)) + 90
  315. if targetYaw < 0 then
  316. targetYaw = targetYaw + 360
  317. end
  318.  
  319. local yawDiff = targetYaw - playerYaw
  320. if yawDiff > 180 then
  321. yawDiff = yawDiff - 360
  322. elseif yawDiff < -180 then
  323. yawDiff = yawDiff + 360
  324. end
  325.  
  326. if math.abs(yawDiff) > 90 then
  327. return nil, nil
  328. end
  329.  
  330. -- Calculate pitch difference
  331. local distXY = math.sqrt(dx * dx + dz * dz)
  332. local targetPitch = math.deg(math.atan2(dy, distXY))
  333. local pitchDiff = targetPitch - playerPitch
  334.  
  335. local screenDepth = screenWidth / 2 * math.tan(math.rad(fov / 1.125 / 2))
  336. local verticalScreenDepth = screenHeight * math.tan(math.rad(fov / 2))
  337.  
  338. local projectedX, projectedY
  339.  
  340. if yawDiff > 0 then
  341. projectedX = screenWidth / 2 + screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  342. else
  343. projectedX = screenWidth / 2 - screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  344. end
  345.  
  346. if pitchDiff > 0 then
  347. projectedY = screenHeight / 2 + screenHeight * math.tan(math.rad(fov / 0.95 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  348. else
  349. projectedY = screenHeight / 2 - screenHeight * math.tan(math.rad(fov / 1.05 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  350. end
  351.  
  352. projectedX = math.floor(projectedX / magicNumber)
  353. projectedY = math.floor(projectedY / magicNumber) + 20
  354.  
  355. return projectedX, projectedY
  356. end
  357.  
  358. -- Function to display pitch and yaw of a cannon
  359. local function angleToScreen(pitch, yaw, userPos, lookVector)
  360. local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
  361. local playerYaw = math.deg(math.atan2(lz, lx))
  362. local playerPitch = math.deg(math.asin(-ly))
  363. playerYaw = playerYaw + 90
  364. if playerYaw < 0 then
  365. playerYaw = playerYaw + 360
  366. end
  367.  
  368. -- Calculate yaw difference
  369. local yawDiff = yaw - playerYaw
  370. if yawDiff > 180 then
  371. yawDiff = yawDiff - 360
  372. elseif yawDiff < -180 then
  373. yawDiff = yawDiff + 360
  374. end
  375.  
  376. if math.abs(yawDiff) > 90 then
  377. return nil, nil
  378. end
  379.  
  380. -- Calculate pitch difference
  381. local pitchDiff = -pitch + playerPitch
  382.  
  383. local screenDepth = screenWidth / 2 * math.tan(math.rad(fov / 1.125 / 2))
  384. local verticalScreenDepth = screenHeight * math.tan(math.rad(fov / 2))
  385.  
  386. local projectedX, projectedY
  387.  
  388. if yawDiff > 0 then
  389. projectedX = screenWidth / 2 + screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  390. else
  391. projectedX = screenWidth / 2 - screenDepth * math.tan(math.rad(math.abs(yawDiff)))
  392. end
  393.  
  394. if pitchDiff > 0 then
  395. projectedY = screenHeight / 2 + screenHeight * math.tan(math.rad(fov / 0.95 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  396. else
  397. projectedY = screenHeight / 2 - screenHeight * math.tan(math.rad(fov / 1.05 / 2)) * math.tan(math.rad(math.abs(pitchDiff)))
  398. end
  399.  
  400. projectedX = math.floor(projectedX / magicNumber)
  401. projectedY = math.floor(projectedY / magicNumber) + 20
  402.  
  403. return projectedX, projectedY
  404. end
  405.  
  406. local function mouseAim(userPos, lookVector)
  407. lookTarget = {}
  408.  
  409. local lx, ly, lz = lookVector[1], lookVector[2], lookVector[3]
  410. local playerYaw = math.deg(math.atan2(lz, lx))
  411. local playerPitch = math.deg(math.asin(-ly))
  412. playerYaw = playerYaw + 90
  413. if playerYaw < 0 then
  414. playerYaw = playerYaw + 360
  415. end
  416.  
  417. local yawRad = math.rad(playerYaw)
  418. local pitchRad = math.rad(playerPitch)
  419.  
  420. local dx = projectionDistance * math.cos(pitchRad) * math.sin(yawRad)
  421. local dz = -projectionDistance * math.cos(pitchRad) * math.cos(yawRad)
  422. local dy = -projectionDistance * math.sin(pitchRad)
  423.  
  424. local targetX = userPos[1] + dx
  425. local targetY = userPos[2] + dy
  426. local targetZ = userPos[3] + dz
  427. lookTarget = { x = targetX, y = targetY, z = targetZ }
  428. return lookTarget
  429. end
  430.  
  431.  
  432. local function isWithinRenderDistance(projectedX, projectedY, centerX, centerY, maxdx, maxdy, maxd)
  433. local dx = projectedX - centerX / magicNumber
  434. local dy = projectedY - centerY / magicNumber
  435.  
  436. if dx < maxdx then
  437. if dy < maxdy then
  438. local distance = math.sqrt(dx * dx + dy * dy)
  439. if distance <= maxd then
  440. return true
  441. else
  442. return false
  443. end
  444. else
  445. return false
  446. end
  447. else
  448. return false
  449. end
  450. end
  451.  
  452. -- Function to check for overlap and adjust positions
  453. local function filterElements(elements)
  454. table.sort(elements, function(a, b) return a.mass > b.mass end) -- Sort by mass
  455. local filteredElements = {}
  456.  
  457. for i, element in ipairs(elements) do
  458. local overlap = false
  459. for _, filteredElement in ipairs(filteredElements) do
  460. local dx = math.abs(element.screenX - filteredElement.screenX)
  461. local dy = math.abs(element.screenY - filteredElement.screenY)
  462. if dx < 800 / GUIscale and dy < 800 / GUIscale then
  463. overlap = true
  464. element.renderInfo = false
  465. break
  466. end
  467. end
  468.  
  469. table.insert(filteredElements, element)
  470.  
  471. end
  472.  
  473. return filteredElements
  474. end
  475.  
  476. -- Function to render elements
  477. local function renderElements(elements, cannonHitPos, pInfo, lockedTarget)
  478. if not holo then return end -- Ensure hologram peripheral is available
  479.  
  480. -- Set the background to transparent
  481. holo.SetClearColor(0x00000000) -- Fully transparent (RGBA: 0,0,0,0)
  482.  
  483. local circleRadius = math.min(screenWidth, screenHeight) / 4
  484.  
  485. -- Iterate through detected objects and render them on the hologram
  486. for _, element in ipairs(elements) do
  487. local color = element.color
  488. local color = element.color
  489. if lockedTarget and element.id == lockedTarget.id then
  490. color = 0xFF0000FF -- Highlight locked target in red
  491. local screenWidth = screenWidth / screenSizeScale
  492. local centerX = screenWidth / 2
  493. local altitudeBoxX = centerX + screenWidth / 6
  494. -- Define the target information to display
  495. local targetInfo = {
  496. "TARGET LOCKED",
  497. "ID: " .. tostring(element.id),
  498. "Speed: " .. tostring(element.speed) .. " m/s",
  499. "Pos: (" ..
  500. string.format("%.0f", element.pos.x) .. "," ..
  501. string.format("%.0f", element.pos.y) .. "," ..
  502. string.format("%.0f", element.pos.z) .. ")",
  503. "Mass: " .. tostring(element.mass) .. " kg",
  504. "Dist: " .. tostring(element.distance) .. " m"
  505. }
  506.  
  507. local missileLaunchedAtTarget = false
  508. if type(controls.fireMissile) == "table" then
  509. for _, missileData in pairs(controls.fireMissile) do
  510. if missileData.type == "ship" and missileData.id == lockedTarget.id then
  511. missileLaunchedAtTarget = true
  512. break
  513. end
  514. end
  515. end
  516.  
  517. -- Add missile launch status to the target info
  518. if missileLaunchedAtTarget then
  519. table.insert(targetInfo, "Missile Launched")
  520. end
  521.  
  522. -- Display each line of the target information
  523. for i, line in ipairs(targetInfo) do
  524. holo.Text(altitudeBoxX, 20 + (i * 15), line, 0xFF000088, 1) -- White text
  525. end
  526. end
  527.  
  528. -- Map screen coordinates to hologram coordinates
  529. local holoX = math.floor(element.screenX / 4) -- Scale down for better fit
  530. local holoY = math.floor(element.screenY / 4) -- Adjust scaling as needed
  531.  
  532. -- Define the size of the box for the target
  533. local boxSize = 6 -- Increase the box size for better visibility
  534.  
  535. -- Ensure the coordinates fit within the hologram display bounds
  536. if holoX >= 0 and holoX < screenWidth / 4 and holoY >= 0 and holoY < screenHeight / 4 and element.renderBox then
  537. -- Draw a bounding box around the detected object
  538. holo.DrawLine(holoX - boxSize, holoY - boxSize, holoX + boxSize, holoY - boxSize, color, 1) -- Top
  539. holo.DrawLine(holoX - boxSize, holoY + boxSize, holoX + boxSize, holoY + boxSize, color, 1) -- Bottom
  540. holo.DrawLine(holoX - boxSize, holoY - boxSize, holoX - boxSize, holoY + boxSize, color, 1) -- Left
  541. holo.DrawLine(holoX + boxSize, holoY - boxSize, holoX + boxSize, holoY + boxSize, color, 1) -- Right
  542.  
  543. if element.renderInfo then
  544. -- Display object ID & distance on the hologram (smaller text)
  545. holo.Text(holoX + boxSize + 2, holoY - boxSize, tostring(element.id), color, 1) -- Target ID
  546. holo.Text(holoX + boxSize + 2, holoY + boxSize, tostring(element.distance) .. "m", color, 1) -- Distance
  547. holo.Text(holoX + boxSize + 2, holoY + boxSize * 3, tostring(element.speed) .. "m/s", color, 1) -- Speed
  548. end
  549. else
  550. -- Draw an edge indicator for objects outside the display bounds
  551. --drawEdgeIndicator(holo, element.screenX, element.screenY, screenWidth / 4, screenHeight / 4, circleRadius)
  552. end
  553. end
  554. end
  555.  
  556. local function lockHighestThreatTarget(elements, centerX, centerY, radius)
  557. local closestTarget = nil
  558. local closestDistance = math.huge -- Initialize to a large number
  559.  
  560. for _, element in ipairs(elements) do
  561. if element.id then
  562. local dx = element.screenX - centerX / magicNumber
  563. local dy = element.screenY - centerY / magicNumber
  564. local distance = math.sqrt(dx * dx + dy * dy)
  565.  
  566. -- Check if the target is within the locking radius on screen
  567. if distance <= radius / GUIscale then
  568. -- If this target is closer to the center than the current closest target, update
  569. if distance < closestDistance then
  570. closestTarget = element
  571. closestDistance = distance
  572. end
  573. end
  574. end
  575. end
  576.  
  577. return closestTarget
  578. end
  579.  
  580. local function modemMessage()
  581. while true do
  582. if modem then
  583. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  584. if channel == cannonHitPosChannel then
  585. cannonHitPos = message
  586. elseif channel == SPAAControlChannel then
  587. controls = message
  588. end
  589. else
  590. sleep()
  591. end
  592. end
  593. end
  594.  
  595. local function getAngularVelocity(currentYaw, currentTime)
  596. if lastYaw and lastYawTime then
  597. local deltaTime = currentTime - lastYawTime
  598. local deltaYaw = (currentYaw - lastYaw + math.pi) % (2 * math.pi) - math.pi
  599. return deltaYaw / deltaTime -- Radians per second
  600. end
  601. return 0
  602. end
  603.  
  604. local function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  605. local radians = math.rad(angle)
  606. local u = projectileSpeed/20
  607. local part1 = u * math.cos(radians) / math.log(cd)
  608. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  609. local XR = part1 * part2
  610.  
  611. return XR
  612. end
  613.  
  614. local function findBestPitch(targetX, targetY, targetZ, sourceX, sourceY, sourceZ, initialVelocity, g, cd, c_est, projectileSpeed)
  615. local bestLowPitch = nil
  616. local bestHighPitch = nil
  617. local bestLowDistance = math.huge
  618. local bestHighDistance = math.huge
  619. local targetDistance = math.sqrt((targetX - sourceX)^2 + (targetZ - sourceZ)^2)
  620.  
  621. for pitch = 0, 70, 0.05 do -- Iterate over pitch angles
  622. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est, projectileSpeed)
  623. local distanceDifference = math.abs(calculatedRange - targetDistance)
  624.  
  625. -- Find the low-angle solution
  626. if pitch <= 30 then
  627. if distanceDifference < bestLowDistance then
  628. bestLowDistance = distanceDifference
  629. bestLowPitch = pitch
  630. end
  631. -- Find the high-angle solution
  632. elseif pitch > 30 then
  633. if distanceDifference < bestHighDistance then
  634. bestHighDistance = distanceDifference
  635. bestHighPitch = pitch
  636. end
  637. end
  638. end
  639.  
  640. --prioritize the low-angle solution
  641. return bestLowPitch
  642. end
  643.  
  644. local function customProportional(error, Kp)
  645. -- Nonlinear proportional scaling
  646. -- Example: Quadratic growth for small errors
  647. local scaleFactor = 0 -- Controls how quickly the value grows for small errors
  648.  
  649. local absError = math.abs(error)
  650. local proportional = Kp * (absError / (1 + scaleFactor * absError)) -- Sigmoid-like growth
  651.  
  652. if error < 0 then
  653. proportional = -proportional -- Preserve the sign of the error
  654. end
  655.  
  656. return math.abs(proportional) * (error < 0 and -1 or 1) -- Cap the value
  657. end
  658.  
  659. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  660. -- Nonlinear proportional term using the custom function
  661. local proportional = customProportional(error, Kp)
  662.  
  663. -- Integral and derivative components
  664. integral = integral + error * dt
  665. local derivative = (error - prevError) / dt
  666.  
  667. -- Calculate the PID output
  668. local output = proportional + (Ki * integral) + (Kd * derivative)
  669.  
  670. -- Return the PID output, updated integral, and current error
  671. return output, integral, error
  672. end
  673.  
  674. -- Yaw control function using PID
  675. local lastYawTime = os.clock()
  676. -- Yaw control function using PID
  677. local function yawControl(deltaYaw, currentYaw)
  678. local now = os.clock()
  679. local dtThisFrame = now - lastYawTime
  680. lastYawTime = now
  681. if dtThisFrame <= 0 then
  682. dtThisFrame = 0.05
  683. end
  684. -- PID controller for yaw
  685. print(dtThisFrame)
  686. local yawSpeed, newIntegral, newPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, deltaYaw, yawIntegral, yawPrevError, dtThisFrame)
  687.  
  688. -- 2) Update global PID state
  689. yawIntegral = newIntegral
  690. yawPrevError = newPrevError
  691.  
  692. -- Constrain the yaw speed to prevent runaway spinning
  693. yawSpeed = math.max(-18, math.min(18, yawSpeed))
  694.  
  695. if controls.accelerate or controls.decelerate then
  696. if controls.turnLeft then
  697. --turn level -1
  698. turnFactor = math.min(turnFactor + 2, 8)
  699. elseif controls.turnRight then
  700. --turn level 1
  701. turnFactor = math.max(turnFactor - 2, -8)
  702. else
  703. if turnFactor > 6 then
  704. turnFactor = turnFactor - 6
  705. elseif turnFactor < -6 then
  706. turnFactor = turnFactor + 6
  707. else
  708. turnFactor = 0
  709. end
  710. end
  711. else
  712. if controls.turnLeft then
  713. --turn level -2
  714. turnFactor = math.min(turnFactor + 2, 10)
  715. elseif controls.turnRight then
  716. --turn level 2
  717. turnFactor = math.max(turnFactor - 2, -10)
  718. else
  719. if turnFactor > 6 then
  720. turnFactor = turnFactor - 6
  721. elseif turnFactor < -6 then
  722. turnFactor = turnFactor + 6
  723. else
  724. turnFactor = 0
  725. end
  726. end
  727. end
  728.  
  729. if controls.decelerate then
  730. turnFactor = -turnFactor
  731. end
  732.  
  733. yawSpeed = yawSpeed + turnFactor
  734.  
  735. print("deltaYaw: " .. deltaYaw)
  736. print("yawSpeed: " .. yawSpeed)
  737.  
  738. -- Set motor speed based on PID output
  739. yawMotor.setTargetSpeed(-yawSpeed)
  740. end
  741.  
  742. local function findRelativeAngle(targetYaw,targetPitch)
  743. rot = ship.getQuaternion()
  744. cacheYaw = math.pi - math.rad(targetYaw)
  745. cachePitch = - math.rad(targetPitch)
  746. rotMatAdj11 = 1 - 2*(rot.x^2 + rot.y^2)
  747. rotMatAdj12 = 2*(rot.z * rot.x + rot.y * rot.w)
  748. rotMatAdj13 = 2*(rot.z * rot.y - rot.x * rot.w)
  749. rotMatAdj21 = 2*(rot.z * rot.x - rot.y * rot.w)
  750. rotMatAdj22 = 1 - 2*(rot.z^2 + rot.y^2)
  751. rotMatAdj23 = 2*(rot.x * rot.y + rot.z * rot.w)
  752. rotMatAdj31 = 2*(rot.z * rot.y + rot.x * rot.w)
  753. rotMatAdj32 = 2*(rot.x * rot.y - rot.z * rot.w)
  754. rotMatAdj33 = 1 - 2*(rot.z^2 + rot.x^2)
  755.  
  756. rotMatTGT11 = math.cos(cacheYaw) * math.cos(cachePitch)
  757. rotMatTGT21 = math.sin(cacheYaw) * math.cos(cachePitch)
  758. rotMatTGT31 = - math.sin(cachePitch)
  759.  
  760. rotMatRSLT11 = rotMatAdj11 * rotMatTGT11 + rotMatAdj12 * rotMatTGT21 + rotMatAdj13 * rotMatTGT31
  761. rotMatRSLT21 = rotMatAdj21 * rotMatTGT11 + rotMatAdj22 * rotMatTGT21 + rotMatAdj23 * rotMatTGT31
  762. rotMatRSLT31 = rotMatAdj31 * rotMatTGT11 + rotMatAdj32 * rotMatTGT21 + rotMatAdj33 * rotMatTGT31
  763.  
  764. turretYaw = math.atan2(rotMatRSLT21, rotMatRSLT11)
  765. barrelPitch = math.asin(-rotMatRSLT31)
  766. return math.deg(-turretYaw),math.deg(-barrelPitch)
  767. end
  768.  
  769. local function setPitchYaw()
  770. while true do
  771. if requiredRelativeYaw and requiredRelativePitch then
  772. local tasks = {} -- Table to store each cannon's task
  773.  
  774. for index, cannon in pairs(cannons) do
  775. -- Define the function for this cannon's pitch/yaw adjustment
  776. local function adjustCannon()
  777. -- Spread logic for other cannons
  778. local spreadConstant = 0
  779.  
  780. local pitchVariation = math.random(-2, 2) * spreadConstant -- Adjust the range to control the spread
  781. local yawVariation = math.random(-2, 2) * spreadConstant -- Adjust the range to control the spread
  782.  
  783. local adjustedPitch = requiredRelativePitch + pitchVariation
  784. local adjustedYaw = requiredRelativeYaw + yawVariation
  785.  
  786. cannon.setPitch(math.min(math.max(adjustedPitch,-50),50))
  787. if controls and controls.cannonControlMode == "mouseAim" then
  788. cannon.setYaw(math.min(math.max(adjustedYaw,-8),8))
  789. end
  790. end
  791.  
  792. -- Add this task to the tasks table
  793. table.insert(tasks, adjustCannon)
  794. end
  795.  
  796. -- Execute all tasks in parallel
  797. parallel.waitForAll(table.unpack(tasks))
  798. end
  799. sleep()
  800. end
  801. end
  802.  
  803. -- Function to predict the future position of the locked target based on its current velocity and time
  804. local function predictFuturePosition(targetPos, targetVel, travelTime)
  805. -- Predict the future position by adding the velocity component scaled by travel time
  806. local dx = targetPos.x - sourceX
  807. local dy = targetPos.y - sourceY
  808. local dz = targetPos.z - sourceZ
  809. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  810.  
  811. local shipVelocity = ship.getVelocity()
  812.  
  813. local estimateTime = distance / (projectileSpeed)
  814. local estimateX = targetPos.x + (targetVel.x * velocityFactor - shipVelocity.x) * estimateTime
  815. local estimateY = targetPos.y + (targetVel.y * velocityFactor - shipVelocity.y) * estimateTime
  816. local estimateZ = targetPos.z + (targetVel.z * velocityFactor - shipVelocity.z) * estimateTime
  817.  
  818. local dx = estimateX - sourceX
  819. local dy = estimateY - sourceY
  820. local dz = estimateZ - sourceZ
  821. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  822.  
  823. local estimateTime = distance / (projectileSpeed)
  824. local estimateX = targetPos.x + (targetVel.x * velocityFactor - shipVelocity.x) * estimateTime
  825. local estimateY = targetPos.y + (targetVel.y * velocityFactor - shipVelocity.y) * estimateTime
  826. local estimateZ = targetPos.z + (targetVel.z * velocityFactor - shipVelocity.z) * estimateTime
  827. return {x = estimateX, y = estimateY, z = estimateZ}
  828. end
  829.  
  830. -- Function to aim the cannon based on the predicted target position
  831. local function aimCannon(targetPos, targetVel, sourceX, sourceY, sourceZ, currentPitch, currentYaw)
  832. if sourceX and sourceY and sourceZ and currentPitch and currentYaw then
  833. -- Perform the future position prediction based on the calculated travel time
  834. local futurePos = predictFuturePosition(targetPos, targetVel)
  835.  
  836. -- Calculate the new dx, dy, dz for the predicted future position
  837. dx = futurePos.x - sourceX
  838. dy = futurePos.y - sourceY
  839. dz = futurePos.z - sourceZ
  840. distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  841.  
  842. -- Calculate the horizontal distance and pitch/yaw adjustments
  843. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  844. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  845. local yaw = math.deg(math.atan2(-dx, dz))
  846. yaw = (yaw + 180) % 360 -- Normalize yaw to range [0, 360)
  847.  
  848. -- Adjust pitch based on distance adjustments
  849. pitch = pitch + findBestPitch(futurePos.x, futurePos.y, futurePos.z, sourceX, sourceY, sourceZ, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  850. pitch = -pitch -- Invert pitch to match the correct cannon direction
  851.  
  852. -- Calculate the yaw error (how much the cannon needs to turn)
  853. local deltaYaw = (yaw - currentYaw + 180) % 360 - 180
  854. local deltaPitch = pitch - currentPitch
  855.  
  856. -- Perform the yaw control and apply the calculated yaw/pitch adjustments
  857. yawControl(deltaYaw, currentYaw)
  858. requiredRelativeYaw, requiredRelativePitch = findRelativeAngle(yaw, -pitch)
  859.  
  860. -- Update the cannon’s yaw and pitch
  861. lastCurrentYaw = currentYaw
  862. lastCurrentPitch = currentPitch
  863. end
  864. end
  865.  
  866.  
  867.  
  868. local function manualCannonControl()
  869. while true do
  870. if controls.cannonControlMode == "manual" then
  871. if controls then
  872. -- Control yaw and pitch manually with arrow keys
  873. if controls.cannonUp then
  874. requiredRelativePitch = requiredRelativePitch + 2
  875. elseif controls.cannonDown then
  876. requiredRelativePitch = requiredRelativePitch - 2
  877. else
  878.  
  879. end
  880. if controls.cannonLeft then
  881. -- Turn left
  882. yawMotor.setTargetSpeed(3)
  883. elseif controls.cannonRight then
  884. -- Turn right
  885. yawMotor.setTargetSpeed(-3)
  886. else
  887. yawMotor.setTargetSpeed(0)
  888. end
  889. else
  890. yawMotor.setTargetSpeed(0)
  891. end
  892. sleep()
  893. else
  894. sleep() -- Sleep for a short time if not in manual mode
  895. end
  896. end
  897. end
  898.  
  899. local function drawCompass()
  900. local yaw = math.deg(getYaw())
  901. if yaw < 0 then
  902. yaw = yaw + 360 -- Ensure yaw is within 0-360
  903. end
  904.  
  905. local screenHeight = screenHeight / screenSizeScale
  906. local screenWidth = screenWidth / screenSizeScale
  907.  
  908. -- Define compass settings
  909. local compassWidth = screenWidth / 2 -- Width of the compass bar
  910. local compassHeight = 8 -- Height for tick marks
  911. local compassY = 10 -- Y position of the compass (top of the screen)
  912. local centerX = screenWidth / 2 -- Center of the screen
  913. local tickSpacing = compassWidth / 36 -- Spacing between ticks (10 degrees per tick)
  914. local labelColor = 0x00FF00FF -- Green color for labels
  915.  
  916. -- Render major directions (N, E, S, W) and tick marks
  917. for angle = -180, 180, 10 do
  918. local relativeAngle = (angle - yaw + 360) % 360 -- Adjust for yaw
  919. local normalizedAngle = relativeAngle > 180 and relativeAngle - 360 or relativeAngle -- Normalize to -180 to 180
  920.  
  921. local posX = math.floor(centerX + (normalizedAngle / 180) * (compassWidth / 2)) -- Map angle to screen
  922.  
  923. if posX >= 0 and posX <= screenWidth then
  924. if angle % 90 == 0 then
  925. -- Major directions (N, E, S, W)
  926. local dir = ({ [0] = "N", [90] = "E", [180] = "S", [-90] = "W", [-180] = "S" })[angle]
  927. holo.Text(posX - 3, compassY + 5, dir, labelColor, 0) -- Label the major directions
  928. holo.DrawLine(posX, compassY, posX, compassY + compassHeight, labelColor, 1) -- Long tick
  929. else
  930. -- Minor tick marks (every 10 degrees)
  931. local tickHeight = compassHeight / 2
  932. holo.DrawLine(posX, compassY, posX, compassY + tickHeight, labelColor, 1)
  933. end
  934. end
  935. end
  936.  
  937. local triangleSize = 3
  938. holo.DrawLine(centerX - triangleSize, compassY, centerX, compassY - compassHeight - 5, labelColor, 1) -- Left edge
  939. holo.DrawLine(centerX, compassY - compassHeight - 5, centerX + triangleSize, compassY, labelColor, 1) -- Right edge
  940. holo.DrawLine(centerX - triangleSize, compassY, centerX + triangleSize, compassY, labelColor, 1) -- Base
  941. end
  942.  
  943. local function renderLockOnArea()
  944. -- Define the center and dimensions
  945. local lockOnRadius = 65 -- Radius of the lock-on circle
  946. local centerX = screenWidth/screenSizeScale / 2
  947. local centerY = screenHeight/screenSizeScale / 2
  948. local color = 0x00FF0088 -- Green color (RGBA format)
  949.  
  950. -- Draw the circle for the lock-on area
  951. for angle = 0, 360, 5 do
  952. local rad = math.rad(angle)
  953. local x1 = math.floor(centerX + lockOnRadius * math.cos(rad))
  954. local y1 = math.floor(centerY + lockOnRadius * math.sin(rad))
  955. local x2 = math.floor(centerX + lockOnRadius * math.cos(math.rad(angle + 5)))
  956. local y2 = math.floor(centerY + lockOnRadius * math.sin(math.rad(angle + 5)))
  957. holo.DrawLine(x1, y1, x2, y2, color, 1)
  958. end
  959. end
  960.  
  961. -- Helper function to clamp values within a specified range
  962. local function clamp(value, min, max)
  963. return math.max(min, math.min(value, max))
  964. end
  965.  
  966. local function renderFuturePosition(futurePos, lockedTarget, pInfo)
  967. if futurePos then
  968. -- Project the future position to screen coords
  969. local screenX, screenY = projectToScreen(futurePos.x, futurePos.y, futurePos.z, pInfo.pos, pInfo.lookVector)
  970.  
  971. -- Ensure screenX and screenY are within valid bounds
  972. if screenX and screenY then
  973. screenX = screenX / 4
  974. screenY = screenY / 4
  975. -- Apply clamping to avoid out-of-bounds coordinates
  976. screenX = clamp(screenX, 0, screenWidth / 4) -- Ensure screenX is within the hologram width
  977. screenY = clamp(screenY, 0, screenHeight / 4) -- Ensure screenY is within the hologram height
  978.  
  979. -- Filter out-of-range screen coords (use your logic here)
  980. if isWithinRenderDistance(
  981. screenX,
  982. screenY,
  983. screenWidth / 8, -- centerX adjusted for hologram scale
  984. screenHeight / 8, -- centerY adjusted for hologram scale
  985. 4000 / GUIscale, -- maxdx
  986. 4800 / GUIscale, -- maxdy
  987. 3200 / GUIscale -- maxd
  988. ) then
  989. -- Proceed if within range
  990. print("screenX:", screenX, "screenY:", screenY)
  991. local circleRadius = 5 -- Smaller circle for future position
  992. local color = 0xFF00FF88 -- Purple color
  993.  
  994. -- Draw a small circle around predicted position
  995. holo.DrawLine(screenX - circleRadius, screenY, screenX + circleRadius, screenY, color, 1)
  996. holo.DrawLine(screenX, screenY - circleRadius, screenX, screenY + circleRadius, color, 1)
  997.  
  998. -- Draw a line connecting locked target to predicted position
  999. if lockedTarget and lockedTarget.pos then
  1000. local targetScreenX, targetScreenY = projectToScreen(
  1001. lockedTarget.pos.x,
  1002. lockedTarget.pos.y,
  1003. lockedTarget.pos.z,
  1004. pInfo.pos,
  1005. pInfo.lookVector
  1006. )
  1007.  
  1008. -- Apply scaling (divide by 4 to match hologram resolution)
  1009. targetScreenX = targetScreenX / 4
  1010. targetScreenY = targetScreenY / 4
  1011.  
  1012. -- Apply clamping to ensure targetScreenX and targetScreenY are valid
  1013. targetScreenX = clamp(targetScreenX, 0, screenWidth / 4)
  1014. targetScreenY = clamp(targetScreenY, 0, screenHeight / 4)
  1015.  
  1016. if targetScreenX and targetScreenY then
  1017. -- Also filter locked target's coords
  1018. if isWithinRenderDistance(
  1019. targetScreenX,
  1020. targetScreenY,
  1021. screenWidth / 8, -- centerX adjusted for hologram scale
  1022. screenHeight / 8, -- centerY adjusted for hologram scale
  1023. 4000 / GUIscale,
  1024. 4800 / GUIscale,
  1025. 3200 / GUIscale
  1026. ) then
  1027. holo.DrawLine(targetScreenX, targetScreenY, screenX, screenY, color, 1)
  1028. end
  1029. end
  1030. end
  1031. end
  1032. end
  1033. end
  1034. end
  1035.  
  1036.  
  1037.  
  1038.  
  1039. local function targetLockAndAim()
  1040. while true do
  1041. currentPitch, currentYaw = math.deg(getPitch()), math.deg(getYaw())
  1042. source = ship.getWorldspacePosition()
  1043.  
  1044. if controls.cannonControlMode == "mouseAim" then
  1045. if pInfo.nickname then
  1046. lockedTarget = lockHighestThreatTarget(elements, screenWidth / 2, screenHeight / 2, 1000)
  1047. if lockedTarget then
  1048. lockedTargetScan = radar.scanForShips(5000)
  1049. for _, object in ipairs(lockedTargetScan) do
  1050. if object.id == lockedTarget.id then
  1051. -- Update the locked target information
  1052. lockedTarget.pos = object.pos
  1053. lockedTarget.velocity = object.velocity
  1054. break
  1055. end
  1056. end
  1057. if lockedTarget.pos then
  1058. -- Predict the future position of the locked target
  1059. local predictionTime = 1.5 -- Predict 1.5 seconds ahead
  1060. local futurePos = predictFuturePosition(lockedTarget.pos, lockedTarget.velocity, predictionTime)
  1061.  
  1062. -- Render the future position with a small circle
  1063. renderFuturePosition(futurePos, lockedTarget, pInfo)
  1064.  
  1065. -- Aim the cannon based on the predicted future position
  1066. aimCannon(futurePos, lockedTarget.velocity, source.x, source.y, source.z, currentPitch, currentYaw)
  1067. end
  1068. else
  1069. lookTarget = mouseAim(pInfo.pos, pInfo.lookVector)
  1070. if lookTarget then
  1071. aimCannon(lookTarget, {x=0, y=0, z=0}, source.x, source.y, source.z, currentPitch, currentYaw)
  1072. end
  1073. end
  1074. end
  1075. end
  1076. sleep()
  1077. end
  1078. end
  1079.  
  1080. -- Update the main function to remove target locking and aiming
  1081. local function main()
  1082. while true do
  1083. holo.Clear()
  1084. local playerList = radar.scanForPlayers(1000)
  1085. parallel.waitForAll(
  1086. function()
  1087. for _, player in ipairs(playerList) do
  1088. local playerName = player.nickname
  1089. local playerPosition = player.pos
  1090. local lookAngle = player.look_angle
  1091.  
  1092. if player.nickname == userID then
  1093. pInfo = {
  1094. nickname = player.nickname,
  1095. pos = player.pos,
  1096. lookVector = lookAngle
  1097. }
  1098. end
  1099. end
  1100.  
  1101. if pInfo.nickname then
  1102. local objectList = radar.scanForShips(10000)
  1103. --ar.clear()
  1104.  
  1105. elements = {}
  1106. for _, object in ipairs(objectList) do
  1107. local objX, objY, objZ = object.pos.x, object.pos.y, object.pos.z
  1108. local screenX, screenY = projectToScreen(objX, objY, objZ, pInfo.pos, pInfo.lookVector)
  1109. 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))
  1110. local speed = math.floor(math.sqrt(object.velocity.x ^ 2 + object.velocity.y ^ 2 + object.velocity.z ^ 2))
  1111. local color
  1112. if isFriendly(object.name) then
  1113. color = 0x009cff88 -- Friendly, blue color
  1114. elseif object.mass < 8000 then
  1115. color = 0x99999988 -- type unknown/low threat
  1116. elseif object.mass < 30000 then
  1117. if speed > 40 then
  1118. -- high speed low mass, potential missile
  1119.  
  1120. local missileVector = {object.velocity.x, object.velocity.y, object.velocity.z}
  1121. local toPlayerVector = {pInfo.pos[1] - objX, pInfo.pos[2] - objY, pInfo.pos[3] - objZ}
  1122. local dotProduct = missileVector[1] * toPlayerVector[1] + missileVector[2] * toPlayerVector[2] + missileVector[3] * toPlayerVector[3]
  1123. if dotProduct > 0 then
  1124. color = 0xff5600ff -- missile coming, high threat
  1125. else
  1126. color = 0xFFFF00ff -- potential threat
  1127. end
  1128. else
  1129. color = 0x00FF0088 -- low mass low speed, low threat
  1130. end
  1131. elseif object.mass < 200000 then
  1132. if speed > 20 then
  1133. color = 0xFFFF00ff -- jet
  1134. else
  1135. color = 0xfff70088 -- Medium sized vehicle, tanks, helicopter
  1136. end
  1137. else
  1138. color = 0xffc300ff -- Large sized vehicle, ships, strategic bomber
  1139. end
  1140.  
  1141. if distance > 20 then
  1142. if screenX and screenY then
  1143. table.insert(elements, {
  1144. id = object.id,
  1145. pos = object.pos,
  1146. screenX = screenX,
  1147. screenY = screenY,
  1148. frameSize = 20,
  1149. color = color,
  1150. distance = distance,
  1151. mass = object.mass,
  1152. speed = speed,
  1153. velocity = object.velocity,
  1154. renderInfo = true,
  1155. renderBox = isWithinRenderDistance(screenX, screenY, screenWidth / 2, screenHeight / 2, 4000 / GUIscale, 4800 / GUIscale, 3200 / GUIscale)
  1156. })
  1157. end
  1158. end
  1159. end
  1160.  
  1161. local filteredElements = filterElements(elements)
  1162.  
  1163. for _, element in ipairs(elements) do
  1164. local found = false
  1165. for _, filteredElement in ipairs(filteredElements) do
  1166. if element.id == filteredElement.id then
  1167. found = true
  1168. break
  1169. end
  1170. end
  1171. if not found then
  1172. element.renderInfo = false
  1173. end
  1174. end
  1175. renderElements(filteredElements, cannonHitPos, pInfo, lockedTarget)
  1176. end
  1177. end,
  1178. drawCompass,
  1179. renderLockOnArea
  1180. )
  1181.  
  1182. if pInfo then
  1183. local AimTarget = mouseAim(pInfo.pos, pInfo.lookVector)
  1184. local screenX, screenY = projectToScreen(AimTarget.x, AimTarget.y, AimTarget.z, pInfo.pos, pInfo.lookVector)
  1185. end
  1186.  
  1187. if ship.getVelocity() then
  1188. local velocity = ship.getVelocity()
  1189. local speed = math.floor(math.sqrt(velocity.x^2 + velocity.y^2 + velocity.z^2))
  1190. end
  1191. holo.Flush()
  1192. sleep()
  1193. end
  1194. end
  1195.  
  1196. local function hitMark()
  1197. while true do
  1198. if cannonHitPos and modem then
  1199. local playerList = radar.scanForPlayers(1000)
  1200. for _, player in ipairs(playerList) do
  1201. local playerName = player.nickname
  1202. local playerPosition = player.pos
  1203. local lookAngle = player.look_angle
  1204.  
  1205. if player.nickname == userID then
  1206. pInfo = {
  1207. nickname = player.nickname,
  1208. pos = player.pos,
  1209. lookVector = lookAngle
  1210. }
  1211. end
  1212. end
  1213.  
  1214. if cannonHitPos[4] == "coordinate" then
  1215. if cannonHitPos then
  1216. objX, objY, objZ = cannonHitPos[1], cannonHitPos[2], cannonHitPos[3]
  1217. end
  1218. if objX and objY and objZ then
  1219. local screenX, screenY = projectToScreen(objX, objY, objZ, pInfo.pos, pInfo.lookVector)
  1220. if screenX and screenY then
  1221. --ar.clearElement("CrossHair")
  1222. --ar.drawStringWithId("CrossHair","X", screenX, screenY, 0xFF0000)
  1223. end
  1224. end
  1225. elseif cannonHitPos[3] == "degree" then
  1226. print("pitch: "..cannonHitPos[1])
  1227. print("yaw: "..cannonHitPos[2])
  1228. local screenX, screenY = angleToScreen(cannonHitPos[1], cannonHitPos[2], pInfo.pos, pInfo.lookVector)
  1229. if screenX and screenY then
  1230. --ar.clearElement("CrossHair")
  1231. --ar.drawStringWithId("CrossHair","X", screenX, screenY, 0xFF0000)
  1232. end
  1233. end
  1234. end
  1235. sleep()
  1236. end
  1237. end
  1238.  
  1239. local function fire()
  1240. while true do
  1241. if controls and controls.fireCannon then
  1242. local tasks = {}
  1243. for index, cannon in pairs(cannons) do
  1244. local function fireCannon()
  1245. cannon.fire()
  1246. cannon.fire()
  1247. cannon.fire()
  1248. cannon.fire()
  1249. end
  1250. table.insert(tasks, fireCannon)
  1251. end
  1252. redstone.setOutput("right",true)
  1253. redstone.setOutput("top",true)
  1254. parallel.waitForAll(table.unpack(tasks))
  1255. else
  1256. redstone.setOutput("right",false)
  1257. redstone.setOutput("top",false)
  1258. end
  1259.  
  1260. if controls and controls.fireAutocannon then
  1261. redstone.setOutput("front",true)
  1262. else
  1263. redstone.setOutput("front",false)
  1264. end
  1265. sleep()
  1266. end
  1267. end
  1268.  
  1269. local function missileLauncherControl()
  1270. local minPitch = -3.1
  1271. local maxPitch = 75.53
  1272.  
  1273. while true do
  1274. if requiredRelativePitch then
  1275. local redstonePower = 15 * (requiredRelativePitch - minPitch) / (maxPitch - minPitch)
  1276. -- Clamp the value between 0 and 15
  1277. if redstonePower < 0 then redstonePower = 0 end
  1278. if redstonePower > 15 then redstonePower = 15 end
  1279.  
  1280. -- Round off to an integer
  1281. redstonePower = math.floor(redstonePower + 0.5)
  1282.  
  1283. redstone.setAnalogOutput("left", redstonePower)
  1284. end
  1285. sleep(0.1)
  1286. end
  1287. end
  1288.  
  1289.  
  1290. -- Main loop
  1291. parallel.waitForAny(
  1292. modemMessage,
  1293. main,
  1294. hitMark,
  1295. targetLockAndAim,
  1296. manualCannonControl,
  1297. fire,
  1298. setPitchYaw,
  1299. missileLauncherControl
  1300. )
  1301.  
Advertisement
Add Comment
Please, Sign In to add comment