MegiRicky

EMBTAim.lua

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