MegiRicky

VerticesMissileControl

Oct 13th, 2024 (edited)
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.41 KB | None | 0 0
  1. local radar = peripheral.find("sp_radar")
  2. local modem = peripheral.find("modem")
  3.  
  4. redstone.setOutput("front",false)
  5. redstone.setOutput("left",false)
  6. redstone.setOutput("bottom",false)
  7. redstone.setOutput("right",false)
  8. redstone.setOutput("back",false)
  9. redstone.setOutput("top",false)
  10.  
  11. local controls = {}
  12. local lockedId = nil
  13. local targetPos, targetVel, TargetYaw, TargetPitch
  14. local Kp_yaw, Ki_yaw, Kd_yaw = 0.15, 0.008, -0.001
  15. local Kp_pitch, Ki_pitch, Kd_pitch = 0.15, 0.03, -0.001
  16. local K_pitchDiff, k_heightDiff = 2,0.5
  17. local projectedMissileY,yLevelDiff,initialDistance,targetAltitude
  18. local closestDistance = math.huge
  19.  
  20. -- Initialize error, integral, and derivative terms for yaw and pitch
  21. local yawError = 0
  22. local yawIntegral = 0
  23. local yawPrevError = 0
  24.  
  25. local pitchError = 0
  26. local pitchIntegral = 0
  27. local pitchHeightPrevError = 0
  28.  
  29. local dt = 0.1
  30. print("Input the missile id, eg:1, default: 1")
  31. local missileId = io.read()
  32. if missileId == "" then
  33. missileId = 1
  34. end
  35. missileId = tonumber(missileId)
  36.  
  37. local controlsChannel = 500
  38. local throttleChannel = controlsChannel + missileId
  39. print("throttleChannel: "..throttleChannel)
  40. if modem then
  41. modem.open(controlsChannel)
  42. modem.open(throttleChannel)
  43. end
  44.  
  45. local function normalizeVector(v)
  46. local length = math.sqrt(v[1] * v[1] + v[2] * v[2] + v[3] * v[3])
  47. if length == 0 then
  48. return {0, 0, 0}
  49. end
  50. return {v[1] / length, v[2] / length, v[3] / length}
  51. end
  52.  
  53. -- Function to normalize the rotation matrix
  54. local function normalizeRotationMatrix(rotMatrix)
  55. local normalizedMatrix = {}
  56. for i = 1, #rotMatrix do
  57. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  58. end
  59. return normalizedMatrix
  60. end
  61.  
  62. -- Modified getPitch function to use the normalized rotation matrix
  63. function getPitch()
  64. local rotMatrix = ship.getRotationMatrix()
  65. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  66. return -math.asin(normalizedMatrix[2][3])
  67. end
  68.  
  69.  
  70. local function modemMessage()
  71. while true do
  72. if modem then
  73. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  74. if channel == controlsChannel then
  75. controls = message
  76. end
  77. else
  78. sleep()
  79. end
  80. end
  81. end
  82.  
  83. local function PIDController(Kp, Ki, Kd, error, integral, derivative, prevError, dt)
  84. -- Calculate the proportional, integral, and derivative components
  85. local proportional = Kp * error
  86. integral = integral + error * dt
  87. derivative = (error - prevError) / dt
  88.  
  89. -- Calculate output
  90. local output = proportional + (Ki * integral) + (Kd * derivative)
  91.  
  92. -- Return the PID output and updated integral and previous error
  93. return output, integral, error
  94. end
  95.  
  96. local function calculateProjectedY(currentY, currentPitch, currentVelocity, distance)
  97. -- Convert pitch to radians for calculation
  98. local pitchRad = math.rad(currentPitch)
  99. -- Estimate the change in Y based on the pitch, velocity, and distance
  100. local projectedY = currentY + math.tan(pitchRad) * distance
  101. return projectedY
  102. end
  103.  
  104. parallel.waitForAny(
  105. function()
  106. while true do
  107. if controls and controls.fireMissile and controls.fireMissile[missileId] and controls.fireMissile[missileId].launch == true then
  108. print("launching")
  109. break
  110. end
  111. sleep()
  112. end
  113. end,
  114. modemMessage
  115. )
  116. print("Scaning for target")
  117.  
  118. --lock on
  119. local targetPos = ship.getWorldspacePosition()
  120. sleep(0.01)
  121. local targetVel = ship.getVelocity()
  122. targetPos.x = targetPos.x + targetVel.x * 2
  123. targetPos.z = targetPos.z + targetVel.y * 2
  124.  
  125. local yaw = math.deg(ship.getYaw())
  126. local pitch = math.deg(ship.getPitch()) * (90/28.6478)
  127.  
  128. local results = radar.scanForShips(2000)
  129. local displayData = {}
  130. print(results)
  131.  
  132. if not results or #results == 0 then
  133. table.insert(displayData, "No objects detected.")
  134. else
  135. local smallestCombinedDiff = math.huge -- Initialize with a large value
  136. local finalTargetYaw = nil
  137. local finalTargetPitch = nil
  138. local finalDistance = nil
  139. local closestDistanceWithSmallDiff = math.huge -- New variable for closest distance with small combined diff
  140.  
  141. -- Assuming 'yaw' and 'pitch' are the current ship's yaw and pitch angles
  142. local pos = ship.getWorldspacePosition()
  143. local yaw = math.deg(ship.getYaw()) + 180
  144. if yaw > 360 then yaw = yaw - 360 end
  145. local pitch = math.deg(getPitch())
  146.  
  147. for i, object in ipairs(results) do
  148. if object.mass > 10000 then
  149. -- Calculate dx, dy, dz from ship to object
  150. local dx = object.pos.x - pos.x
  151. local dy = object.pos.y - pos.y
  152. local dz = object.pos.z - pos.z
  153.  
  154. -- Calculate bearing (yaw) from ship to object
  155. local angleFromSouth = math.atan2(dx, dz)
  156. local bearingFromSouth = math.deg(angleFromSouth)
  157. local targetYaw = (180 - bearingFromSouth) % 360
  158.  
  159. -- Calculate yaw difference
  160. local yawDiff = (targetYaw - yaw + 180) % 360 - 180
  161.  
  162. -- Calculate pitch difference
  163. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  164. local targetPitch = math.deg(math.atan2(dy, horizontalDistance))
  165. local pitchDiff = targetPitch - (-pitch)
  166.  
  167. -- Calculate the Euclidean distance (for prioritization)
  168. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  169.  
  170. -- Combine yaw and pitch differences into a single score (weighted sum or simply adding)
  171. local combinedDiff = math.abs(yawDiff) + math.abs(pitchDiff)
  172.  
  173. -- Additional logic: If combinedDiff is less than 20, lock onto the closest target
  174. if combinedDiff < 40 then
  175. if distance < closestDistanceWithSmallDiff then
  176. closestDistanceWithSmallDiff = distance
  177. lockedId = object.id
  178. intialPosition = object.pos
  179. initialDistance = horizontalDistance
  180. print("Target with combinedDiff < 20, Distance: ", distance, " Locked target ID: ", object.id)
  181. end
  182. end
  183. end
  184. end
  185.  
  186. if lockedId and intialPosition then
  187. print("Closest Object ID:", lockedId)
  188. print("X: "..intialPosition.x.." Y: "..intialPosition.y.." Z: "..intialPosition.z)
  189. print("initialDistance: "..initialDistance)
  190. else
  191. print("No large objects detected.")
  192. end
  193. end
  194.  
  195. print("Locked Target:", lockedId)
  196. print("X: "..intialPosition.x.." Y: "..intialPosition.y.." Z: "..intialPosition.z)
  197. modem.transmit(throttleChannel, 0, 5)
  198. sleep(1)
  199. modem.transmit(throttleChannel, 0, 0)
  200.  
  201. local function initial()
  202. local results = radar.scanForShips(2000)
  203. pos = ship.getWorldspacePosition()
  204. local yaw = math.deg(ship.getYaw()) + 180
  205. if yaw>360 then yaw = yaw - 360 end
  206. local missileVelocity = ship.getVelocity()
  207. local misisleSpeed = math.sqrt(missileVelocity.x ^ 2 + missileVelocity.y ^ 2 + missileVelocity.z ^ 2)
  208. local pitch = math.deg(getPitch())
  209. local flightControl = {
  210. pitchUp = nil, pitchDown, yawLeft = nil, yawRight = nil, throttle = nil
  211. }
  212. print("pitch: "..pitch)
  213. for i, object in ipairs(results) do
  214. if object.id == lockedId then
  215. targetPos = object.pos
  216. targetVel = object.velocity
  217. local dx = targetPos.x - pos.x
  218. local dy = targetPos.y - pos.y
  219. local dz = targetPos.z - pos.z
  220. local immediateDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  221. missileSpeed = math.sqrt(missileVelocity.x^2 + missileVelocity.y^2 + missileVelocity.z^2)
  222. if missileSpeed < 0.1 then missileSpeed = 0.1 end
  223.  
  224. -- Update pitch, yaw, and distance
  225. local estimateTime = immediateDistance/missileSpeed
  226. local estimateX = targetPos.x + targetVel.x * estimateTime
  227. local estimateY = targetPos.y + targetVel.y * estimateTime
  228. local estimateZ = targetPos.z + targetVel.z * estimateTime
  229.  
  230. local dx = estimateX - pos.x
  231. local dy = estimateY - pos.y
  232. local dz = estimateZ - pos.z
  233.  
  234. local targetHorizontalDistance = math.sqrt(dx * dx + dz * dz)
  235.  
  236. TargetYaw = math.deg(math.atan2(-dx, dz))
  237. TargetYaw = (TargetYaw + 180) % 360
  238.  
  239. projectedMissileY = pos.y + missileVelocity.y * estimateTime
  240. yLevelDiff = targetPos.y - projectedMissileY
  241. TargetPitch = math.deg(math.atan2(dy, targetHorizontalDistance))
  242.  
  243. targetAltitude = targetPos.y
  244.  
  245. yawError = TargetYaw - yaw
  246. pitchError = TargetPitch - (-pitch)
  247. pitchHeightDiff = pitchError * K_pitchDiff + yLevelDiff * k_heightDiff
  248. print(pitch)
  249.  
  250. -- Output diagnostics
  251. end
  252. end
  253.  
  254. -- Ensure yaw is between -180 and 180 for error
  255. if yawError > 180 then
  256. yawError = yawError - 360
  257. elseif yawError < -180 then
  258. yawError = yawError + 360
  259. end
  260.  
  261. -- PID control for yaw
  262. local yawOutput, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, yawError, yawIntegral, (yawError - yawPrevError), yawPrevError, dt)
  263. yawOutput = math.min(math.max(yawOutput, -15), 15)
  264. if -pitch > 30 or pos.y - targetAltitude > 50 then
  265. pitchOutput = -1
  266. else
  267. pitchOutput = 3
  268. end
  269.  
  270. --yaw and pitch flight control
  271. if yawOutput > 0 then
  272. redstone.setOutput("right", true)
  273. redstone.setOutput("left", false)
  274. redstone.setAnalogOutput("right", math.abs(yawOutput))
  275. elseif yawOutput < 0 then
  276. redstone.setOutput("left", true)
  277. redstone.setOutput("right", false)
  278. redstone.setAnalogOutput("left", math.abs(yawOutput))
  279. else
  280. redstone.setOutput("right", false)
  281. redstone.setOutput("left", false)
  282. end
  283.  
  284. if pitchOutput > 0.1 then
  285. local adjustedPitchOutput = math.max(math.abs(pitchOutput),1)
  286. redstone.setOutput("top", true)
  287. redstone.setOutput("bottom", false)
  288. redstone.setAnalogOutput("top", math.min(adjustedPitchOutput, 15))
  289. elseif pitchOutput < -0.1 then
  290. local adjustedPitchOutput = math.max(math.abs(pitchOutput),1)
  291. redstone.setOutput("bottom", true)
  292. redstone.setOutput("top", false)
  293. redstone.setAnalogOutput("bottom", math.min(adjustedPitchOutput, 15))
  294. else
  295. redstone.setOutput("top", false)
  296. redstone.setOutput("bottom", false)
  297. end
  298.  
  299.  
  300. --throttle control
  301. if missileSpeed < 60 then
  302. modem.transmit(throttleChannel, 0, 1) -- Increase throttle
  303. else
  304. modem.transmit(throttleChannel, 0, 0)
  305. end
  306. end
  307.  
  308. local function terminal()
  309. local results = radar.scanForShips(2000)
  310. pos = ship.getWorldspacePosition()
  311. local yaw = math.deg(ship.getYaw()) + 180
  312. if yaw>360 then yaw = yaw - 360 end
  313. local missileVelocity = ship.getVelocity()
  314. local misisleSpeed = math.sqrt(missileVelocity.x ^ 2 + missileVelocity.y ^ 2 + missileVelocity.z ^ 2)
  315. local pitch = math.deg(getPitch())
  316. local flightControl = {
  317. pitchUp = nil, pitchDown, yawLeft = nil, yawRight = nil, throttle = nil
  318. }
  319. for i, object in ipairs(results) do
  320. if object.id == lockedId then
  321. -- Update position and targetVel
  322. targetPos = object.pos
  323. targetVel = object.velocity
  324. local dx = targetPos.x - pos.x
  325. local dy = targetPos.y - pos.y
  326. local dz = targetPos.z - pos.z
  327. local immediateDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  328. missileSpeed = math.sqrt(missileVelocity.x^2 + missileVelocity.y^2 + missileVelocity.z^2)
  329. if missileSpeed < 0.1 then missileSpeed = 0.1 end
  330.  
  331. -- Update pitch, yaw, and distance
  332. local estimateTime = immediateDistance/missileSpeed
  333. local estimateX = targetPos.x + targetVel.x * estimateTime
  334. local estimateY = targetPos.y + targetVel.y * estimateTime
  335. local estimateZ = targetPos.z + targetVel.z * estimateTime
  336.  
  337. local dx = estimateX - pos.x
  338. local dy = estimateY - pos.y
  339. local dz = estimateZ - pos.z
  340.  
  341. local targetHorizontalDistance = math.sqrt(dx * dx + dz * dz)
  342.  
  343. TargetYaw = math.deg(math.atan2(-dx, dz))
  344. TargetYaw = (TargetYaw + 180) % 360
  345.  
  346. projectedMissileY = pos.y + missileVelocity.y * estimateTime
  347. yLevelDiff = targetPos.y - projectedMissileY
  348. TargetPitch = math.deg(math.atan2(dy, targetHorizontalDistance))
  349.  
  350. yawError = TargetYaw - yaw
  351. pitchError = TargetPitch - (-pitch)
  352.  
  353. pitchHeightDiff = pitchError * K_pitchDiff + yLevelDiff * k_heightDiff
  354. print(pitch)
  355. -- Output diagnostics
  356. end
  357. end
  358.  
  359. -- Ensure yaw is between -180 and 180 for error
  360. if yawError > 180 then
  361. yawError = yawError - 360
  362. elseif yawError < -180 then
  363. yawError = yawError + 360
  364. end
  365.  
  366. -- PID control for yaw
  367. local yawOutput, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, yawError, yawIntegral, (yawError - yawPrevError), yawPrevError, dt)
  368. yawOutput = math.min(math.max(yawOutput, -15), 15)
  369.  
  370. -- PID control for pitch
  371. local pitchOutput, pitchIntegral, pitchHeightPrevError = PIDController(Kp_pitch, Ki_pitch, Kd_pitch, pitchHeightDiff, pitchIntegral, (pitchHeightDiff - pitchHeightPrevError), pitchHeightPrevError, dt)
  372. pitchOutput = math.min(math.max(pitchOutput, -15), 15)
  373. print("yawOutput: "..yawOutput.." pitchOutput: "..pitchOutput)
  374.  
  375. --yaw and pitch flight control
  376. if yawOutput > 0 then
  377. redstone.setOutput("right", true)
  378. redstone.setOutput("left", false)
  379. redstone.setAnalogOutput("right", math.abs(yawOutput))
  380. elseif yawOutput < 0 then
  381. redstone.setOutput("left", true)
  382. redstone.setOutput("right", false)
  383. redstone.setAnalogOutput("left", math.abs(yawOutput))
  384. else
  385. redstone.setOutput("right", false)
  386. redstone.setOutput("left", false)
  387. end
  388.  
  389. if pitchOutput > 0.1 then
  390. local adjustedPitchOutput = math.max(math.abs(pitchOutput),1)
  391. redstone.setOutput("top", true)
  392. redstone.setOutput("bottom", false)
  393. redstone.setAnalogOutput("top", math.min(adjustedPitchOutput, 15))
  394. elseif pitchOutput < -0.1 then
  395. local adjustedPitchOutput = math.max(math.abs(pitchOutput),1)
  396. redstone.setOutput("bottom", true)
  397. redstone.setOutput("top", false)
  398. redstone.setAnalogOutput("bottom", math.min(adjustedPitchOutput, 15))
  399. else
  400. redstone.setOutput("top", false)
  401. redstone.setOutput("bottom", false)
  402. end
  403.  
  404. --throttle control
  405. if yawOutput > 5 or yLevelDiff > 5 then
  406. if missileSpeed < 50 then
  407. modem.transmit(throttleChannel, 0, 1) -- Increase throttle
  408. else
  409. modem.transmit(throttleChannel, 0, 0)
  410. end
  411. else
  412. if missileSpeed < 50 then
  413. modem.transmit(throttleChannel, 0, 1) -- Increase throttle
  414. else
  415. modem.transmit(throttleChannel, 0, 0)
  416. end
  417. end
  418. end
  419.  
  420. local function fuze()
  421. local results = radar.scanForShips(2000)
  422. pos = ship.getWorldspacePosition()
  423. local distance
  424. for i, object in ipairs(results) do
  425. if object.id == lockedId then
  426. targetPos = object.pos
  427. local dx = targetPos.x - pos.x
  428. local dy = targetPos.y - pos.y
  429. local dz = targetPos.z - pos.z
  430.  
  431. distance = math.sqrt(dx * dx + dy * dy +dz * dz)
  432. end
  433. end
  434. if distance > closestDistance then
  435. print("detonating")
  436. redstone.setOutput("back",true)
  437. sleep(0.1)
  438. redstone.setOutput("front",false)
  439. redstone.setOutput("left",false)
  440. redstone.setOutput("bottom",false)
  441. redstone.setOutput("right",false)
  442. redstone.setOutput("back",false)
  443. redstone.setOutput("top",false)
  444. modem.transmit(throttleChannel, 0, 0)
  445. error("detonated")
  446. else
  447. closestDistance = distance
  448. end
  449.  
  450. if redstone.getInput("front") then
  451. print("detonating")
  452. redstone.setOutput("back",true)
  453. sleep(0.1)
  454. redstone.setOutput("front",false)
  455. redstone.setOutput("left",false)
  456. redstone.setOutput("bottom",false)
  457. redstone.setOutput("right",false)
  458. redstone.setOutput("back",false)
  459. redstone.setOutput("top",false)
  460. modem.transmit(throttleChannel, 0, 0)
  461. error("detonated")
  462. end
  463. end
  464.  
  465. while true do
  466. local results = radar.scanForShips(2000)
  467. pos = ship.getWorldspacePosition()
  468. for i, object in ipairs(results) do
  469. if object.id == lockedId then
  470. targetPos = object.pos
  471. local dx = targetPos.x - pos.x
  472. local dy = targetPos.y - pos.y
  473. local dz = targetPos.z - pos.z
  474.  
  475. horizontalDistance = math.sqrt(dx * dx + dz * dz)
  476. end
  477. end
  478. print("horizontalDistance"..horizontalDistance)
  479. if horizontalDistance < 80 then
  480. print("terminal phrase")
  481. terminal()
  482. fuze()
  483. else
  484. print("initial phrase")
  485. initial()
  486. end
  487. end
  488.  
  489.  
  490.  
  491.  
Advertisement
Add Comment
Please, Sign In to add comment