MegiRicky

AIM-220V2P2Contro.lua

Jul 25th, 2025 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.07 KB | None | 0 0
  1. --//pastebin get YvDHBkZy missileAIM220V2P2
  2.  
  3. local radar = peripheral.find("sp_radar")
  4. local modem = peripheral.wrap("right")
  5. local topFlap = peripheral.wrap("top")
  6. local bottomFlap = peripheral.wrap("bottom")
  7. local leftFlap = peripheral.wrap("back")
  8. local rightFlap = peripheral.wrap("front")
  9.  
  10. while not radar do
  11. print("Radar not connected, reset needed")
  12. radar = peripheral.find("sp_radar")
  13. sleep(0.5)
  14. end
  15.  
  16. redstone.setOutput("front",false)
  17. redstone.setOutput("left",false)
  18. redstone.setOutput("bottom",false)
  19. redstone.setOutput("right",false)
  20. redstone.setOutput("back",false)
  21. redstone.setOutput("top",false)
  22.  
  23. local controls = {}
  24. local target = {}
  25. local lockedId = nil
  26. local targetPos, targetVel, TargetYaw, TargetPitch
  27. local Kp_yaw, Ki_yaw, Kd_yaw = 0.15, 0, 0.005
  28. local Kp_pitch, Ki_pitch, Kd_pitch = 0.18, 0, 0.005
  29. local Kp_roll, Ki_roll,Kd_roll = 0.02,0,0
  30. local Kp_throttle, Ki_throttle, Kd_throttle = 0.2, 0.1, 0.02
  31. local K_pitchDiff, k_heightDiff = 1,0
  32. local projectedMissileY,yLevelDiff,initialDistance,targetAltitude
  33. local closestDistance = math.huge
  34.  
  35. local highThrust = 15
  36.  
  37. -- Initialize error, integral, and derivative terms for yaw and pitch
  38. local yawError = 0
  39. local yawIntegral = 0
  40. local yawPrevError = 0
  41.  
  42. local pitchError = 0
  43. local pitchIntegral = 0
  44. local pitchPrevError = 0
  45.  
  46. local rollError,rollIntegral,rollPrevError = 0,0,0
  47.  
  48. local dt = 0.1
  49.  
  50. local deltaDistance = 0
  51. local lastDistance = 0
  52. local lastTime = os.clock()
  53.  
  54. local controlsChannel = 1400
  55. local missileInfoChannel = controlsChannel + 10
  56. if modem then
  57. modem.open(controlsChannel)
  58. modem.open(missileInfoChannel)
  59. end
  60.  
  61. -- Normalize a vector
  62. local function normalizeVector(v)
  63. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  64. if length == 0 then
  65. return {0, 0, 0}
  66. end
  67. return {v[1] / length, v[2] / length, v[3] / length}
  68. end
  69.  
  70. -- Normalize the rotation matrix
  71. local function normalizeRotationMatrix(rotMatrix)
  72. local normalizedMatrix = {}
  73. for i = 1, #rotMatrix do
  74. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  75. end
  76. return normalizedMatrix
  77. end
  78.  
  79. -- Get the pitch of the ship
  80. local function getPitch()
  81. local rotMatrix = ship.getTransformationMatrix()
  82. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  83. return -math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  84. end
  85.  
  86. -- Get the yaw of the ship
  87. local function getYaw()
  88. local rotMatrix = ship.getTransformationMatrix()
  89. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  90. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  91. end
  92.  
  93. -- Get the roll of the ship
  94. local function getRoll()
  95. local rotMatrix = ship.getTransformationMatrix()
  96. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  97. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  98. end
  99.  
  100. local function modemMessage()
  101. while true do
  102. if modem then
  103. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  104. if channel == controlsChannel then
  105. controls = message
  106. end
  107. else
  108. sleep()
  109. end
  110. end
  111. end
  112.  
  113. local function PIDController(Kp, Ki, Kd, error, integral, derivative, prevError, dt)
  114. -- Calculate the proportional, integral, and derivative components
  115. local proportional = Kp * error
  116. integral = integral + error * dt
  117. derivative = (error - prevError) / dt
  118.  
  119. -- Calculate output
  120. local output = proportional + (Ki * integral) + (Kd * derivative)
  121.  
  122. -- Return the PID output and updated integral and previous error
  123. return output, integral, error
  124. end
  125.  
  126. local function calculateProjectedY(currentY, currentPitch, currentVelocity, distance)
  127. -- Convert pitch to radians for calculation
  128. local pitchRad = math.rad(currentPitch)
  129. -- Estimate the change in Y based on the pitch, velocity, and distance
  130. local projectedY = currentY + math.tan(pitchRad) * distance
  131. return projectedY
  132. end
  133.  
  134. local function broadCastid()
  135. while true do
  136. local id = ship.getId()
  137. local slug = ship.getName()
  138. local missileInfo = {id = id, type = "AIM-220", launchState = false, slug = slug}
  139. modem.transmit(missileInfoChannel,0,missileInfo)
  140. print("Broadcasting missile info at channel: "..missileInfoChannel)
  141. print("Radar ready, ready for launch")
  142. sleep()
  143. end
  144. end
  145.  
  146. parallel.waitForAny(
  147. function()
  148. while true do
  149. --print("controls: "..textutils.serialize(controls))
  150. missileId = ship.getId()
  151. if controls and controls.fireMissile and controls.fireMissile[missileId] and controls.fireMissile[missileId].launch == true then
  152. target = controls.fireMissile[missileId]
  153. print("launching")
  154. break
  155. end
  156. sleep()
  157. end
  158. end,
  159. modemMessage,
  160. broadCastid
  161. )
  162. print("Scaning for target")
  163.  
  164. local function broadCastid()
  165. while true do
  166. local id = ship.getId()
  167. local slug = ship.getName()
  168. local missileInfo = {id = id, type = "AIM-220", launchState = true, slug = slug}
  169. modem.transmit(missileInfoChannel,0,missileInfo)
  170. sleep()
  171. end
  172. end
  173.  
  174. --lock on
  175. local results = radar.scanForShips(4000)
  176. local displayData = {}
  177. print(textutils.serialize(target))
  178.  
  179. local fastestSpeed = 0
  180.  
  181. if target.type == "ship" then
  182. if not results or #results == 0 then
  183. table.insert(displayData, "No objects detected.")
  184. else
  185. local smallestCombinedDiff = math.huge -- Initialize with a large value
  186. local finalTargetYaw = nil
  187. local finalTargetPitch = nil
  188. local finalDistance = nil
  189. local closestDistanceWithSmallDiff = math.huge -- New variable for closest distance with small combined diff
  190.  
  191. -- Assuming 'yaw' and 'pitch' are the current ship's yaw and pitch angles
  192. local pos = ship.getWorldspacePosition()
  193. local yaw = math.deg(getYaw()) + 180
  194. if yaw > 360 then yaw = yaw - 360 end
  195. local pitch = math.deg(getPitch())
  196.  
  197. for i, object in ipairs(results) do
  198. -- Calculate dx, dy, dz from ship to object
  199. local dx = object.pos.x - pos.x
  200. local dy = object.pos.y - pos.y
  201. local dz = object.pos.z - pos.z
  202.  
  203. -- Calculate bearing (yaw) from ship to object
  204. local angleFromSouth = math.atan2(dx, dz)
  205. local bearingFromSouth = math.deg(angleFromSouth)
  206. local targetYaw = (180 - bearingFromSouth) % 360
  207.  
  208. -- Calculate yaw difference
  209. local yawDiff = (targetYaw - yaw + 180) % 360 - 180
  210.  
  211. -- Calculate pitch difference
  212. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  213. local targetPitch = math.deg(math.atan2(dy, horizontalDistance))
  214. local pitchDiff = targetPitch - (-pitch)
  215.  
  216. -- Calculate the Euclidean distance (for prioritization)
  217. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  218.  
  219. -- Combine yaw and pitch differences into a single score (weighted sum or simply adding)
  220. local combinedDiff = math.abs(yawDiff) + math.abs(pitchDiff)
  221.  
  222. -- Additional logic: If combinedDiff is less than 20, lock onto the closest target
  223. if object.id == target.id then
  224. closestDistanceWithSmallDiff = distance
  225. lockedId = object.id
  226. intialPosition = object.pos
  227. initialDistance = horizontalDistance
  228. print("Target with combinedDiff < 20, Distance: ", distance, " Locked target ID: ", object.id)
  229. end
  230. end
  231.  
  232. if lockedId and intialPosition then
  233. print("Closest Object ID:", lockedId)
  234. print("X: "..intialPosition.x.." Y: "..intialPosition.y.." Z: "..intialPosition.z)
  235. print("initialDistance: "..initialDistance)
  236. else
  237. print("Target not dectected")
  238. end
  239. end
  240. else
  241. local pos = ship.getWorldspacePosition()
  242. local dx = target.pos.x - pos.x
  243. local dy = target.pos.y - pos.y
  244. local dz = target.pos.z - pos.z
  245. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  246. intialPosition = target.pos
  247. initialDistance = math.sqrt(dx * dx + dz * dz)
  248. end
  249.  
  250. print("Locked Target:", lockedId)
  251. print("X: "..intialPosition.x.." Y: "..intialPosition.y.." Z: "..intialPosition.z)
  252. topFlap.assemble()
  253. bottomFlap.assemble()
  254. leftFlap.assemble()
  255. rightFlap.assemble()
  256.  
  257. redstone.setAnalogOutput("top",highThrust)
  258. redstone.setOutput("bottom",true)
  259. sleep(0.3)
  260. redstone.setAnalogOutput("top",0)
  261. redstone.setOutput("bottom",false)
  262.  
  263. local function initial()
  264. local results = radar.scanForShips(4000)
  265. pos = ship.getWorldspacePosition()
  266. local yaw = math.deg(getYaw())
  267. if yaw>360 then yaw = yaw - 360 end
  268. local missileVelocity = ship.getVelocity()
  269. local misisleSpeed = math.sqrt(missileVelocity.x ^ 2 + missileVelocity.y ^ 2 + missileVelocity.z ^ 2)
  270. local pitch = math.deg(getPitch())
  271. local flightControl = {
  272. pitchUp = nil, pitchDown, yawLeft = nil, yawRight = nil, throttle = nil
  273. }
  274.  
  275. if target.type == "ship" then
  276. for i, object in ipairs(results) do
  277. if object.id == lockedId then
  278. targetPos = object.pos
  279. targetVel = object.velocity
  280. local dx = targetPos.x - pos.x
  281. local dy = targetPos.y - pos.y + 50
  282. local dz = targetPos.z - pos.z
  283. local immediateDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  284. missileSpeed = math.sqrt(missileVelocity.x^2 + missileVelocity.y^2 + missileVelocity.z^2)
  285. if missileSpeed < 0.1 then missileSpeed = 0.1 end
  286.  
  287. -- Update pitch, yaw, and distance
  288. local estimateTime = immediateDistance/missileSpeed
  289. local estimateX = targetPos.x + targetVel.x * math.min(estimateTime,1)
  290. local estimateY = targetPos.y + 50
  291. local estimateZ = targetPos.z + targetVel.z * math.min(estimateTime,1)
  292.  
  293. local dx = estimateX - pos.x
  294. local dy = estimateY - pos.y
  295. local dz = estimateZ - pos.z
  296.  
  297. local targetHorizontalDistance = math.sqrt(dx * dx + dz * dz)
  298.  
  299. TargetYaw = math.deg(math.atan2(-dx, dz))
  300. TargetYaw = (TargetYaw + 180) % 360
  301.  
  302. projectedMissileY = pos.y + missileVelocity.y * estimateTime
  303. yLevelDiff = targetPos.y - projectedMissileY
  304. TargetPitch = math.deg(math.atan2(dy, targetHorizontalDistance))
  305.  
  306. targetAltitude = targetPos.y
  307.  
  308. yawError = TargetYaw - yaw
  309. pitchError = TargetPitch - (-pitch)
  310. rollError = math.deg(getRoll())
  311.  
  312. pitchHeightDiff = pitchError * K_pitchDiff + yLevelDiff * k_heightDiff
  313. end
  314. end
  315. elseif target.type == "waypoint" then
  316. targetPos = target.pos
  317.  
  318. local dx = targetPos.x - pos.x
  319. local dy = targetPos.y - pos.y + 100
  320. local dz = targetPos.z - pos.z
  321. local immediateDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  322. missileSpeed = math.sqrt(missileVelocity.x^2 + missileVelocity.y^2 + missileVelocity.z^2)
  323. if missileSpeed < 0.1 then missileSpeed = 0.1 end
  324.  
  325. local estimateTime = immediateDistance/missileSpeed
  326.  
  327. local targetHorizontalDistance = math.sqrt(dx * dx + dz * dz)
  328.  
  329. TargetYaw = math.deg(math.atan2(-dx, dz))
  330. TargetYaw = (TargetYaw + 180) % 360
  331.  
  332. projectedMissileY = pos.y + missileVelocity.y * estimateTime
  333. yLevelDiff = targetPos.y - projectedMissileY
  334. TargetPitch = math.deg(math.atan2(dy, targetHorizontalDistance))
  335.  
  336. targetAltitude = targetPos.y
  337.  
  338. yawError = TargetYaw - yaw
  339. pitchError = TargetPitch - (-pitch)
  340. pitchHeightDiff = pitchError * K_pitchDiff + yLevelDiff * k_heightDiff
  341. print(pitch)
  342. end
  343.  
  344. -- Ensure yaw is between -180 and 180 for error
  345. if yawError > 180 then
  346. yawError = yawError - 360
  347. elseif yawError < -180 then
  348. yawError = yawError + 360
  349. end
  350.  
  351. -- PID control for yaw
  352. local yawOutput, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, yawError, yawIntegral, (yawError - yawPrevError), yawPrevError, dt)
  353. yawOutput = -math.min(math.max(yawOutput, -45), 45) / (1+math.abs(rollError)*0.1)
  354.  
  355. local pitchOutput, pitchIntegral, pitchHeightPrevError = PIDController(Kp_pitch, Ki_pitch, Kd_pitch, pitchHeightDiff, pitchIntegral, (pitchHeightDiff - pitchHeightPrevError), pitchHeightPrevError, dt)
  356. pitchOutput = -math.min(math.max(pitchOutput, -30), 30) / (1+math.abs(rollError)*0.1)
  357.  
  358. local rollOutput,rollIntegral,rollPrevError = PIDController(Kp_roll, Ki_roll, Kd_roll, rollError, rollIntegral, (rollError - rollPrevError), rollPrevError, dt)
  359. rollOutput = -math.min(math.max(rollOutput, -10), 10)
  360.  
  361. --yaw and pitch flight control
  362. if missileSpeed < 40 then --adjustment for yaw propeller bug
  363. yawOutput = yawOutput
  364. pitchOutput = pitchOutput * 2.3
  365. rollOutput = rollOutput
  366. end
  367.  
  368.  
  369. if yawOutput > 0 then
  370. topFlap.setAngle(yawOutput)
  371. bottomFlap.setAngle(yawOutput)
  372. elseif yawOutput < 0 then
  373. topFlap.setAngle(yawOutput)
  374. bottomFlap.setAngle(yawOutput)
  375. else
  376. topFlap.setAngle(0)
  377. bottomFlap.setAngle(0)
  378. end
  379.  
  380. if pitchOutput > 0.1 then
  381. leftFlap.setAngle(pitchOutput + rollOutput)
  382. rightFlap.setAngle(pitchOutput - rollOutput)
  383. elseif pitchOutput < -0.1 then
  384. leftFlap.setAngle(pitchOutput + rollOutput)
  385. rightFlap.setAngle(pitchOutput - rollOutput)
  386. else
  387. leftFlap.setAngle(0)
  388. rightFlap.setAngle(0)
  389. end
  390.  
  391. if missileSpeed < 60 then
  392. print("Speed below optimal, accelerating")
  393. redstone.setAnalogOutput("top",highThrust)
  394. else
  395. if yawOutput > 8 or pitchOutput > 8 or missileSpeed then
  396. redstone.setAnalogOutput("top",0)
  397. end
  398. end
  399. end
  400.  
  401. local lastTargetPos, lastTargetVelocity, predictedTargetVelocity, predictedTargetAcceleration
  402. local lastTargetAqquireTime = os.clock()
  403.  
  404. local function clampVectorMagnitude(vec, maxMag)
  405. local mag = math.sqrt(vec.x^2 + vec.y^2 + vec.z^2)
  406. if mag > maxMag then
  407. local scale = maxMag / mag
  408. return {
  409. x = vec.x * scale,
  410. y = vec.y * scale,
  411. z = vec.z * scale
  412. }
  413. end
  414. return vec
  415. end
  416.  
  417. local lastTargetPos, lastTargetVelocity, predictedTargetVelocity, predictedTargetAcceleration
  418. local lastTargetAqquireTime = os.clock()
  419.  
  420. local function predictFuturePosition(targetPos, targetVel, sourceX, sourceY, sourceZ, missileSpeed)
  421. local currentTime = os.clock()
  422. local dt = currentTime - lastTargetAqquireTime
  423.  
  424. -- Compute initial distance to target
  425. local dx = targetPos.x - sourceX
  426. local dy = targetPos.y - sourceY
  427. local dz = targetPos.z - sourceZ
  428. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  429.  
  430. -- Get ship's velocity
  431. local shipVelocity = ship.getVelocity()
  432. predictedTargetAcceleration = {x = 0, y = 0, z = 0}
  433. -- Initial estimate for travel time
  434. local estimateTime = distance / missileSpeed
  435. estimateTime = math.min(math.max(estimateTime,0.01),100)
  436.  
  437. -- Predict future position using velocity and acceleration
  438. local estimateX = targetPos.x
  439. + (targetVel.x) * estimateTime
  440. + 0.5 * predictedTargetAcceleration.x * estimateTime * estimateTime
  441.  
  442. local estimateY = targetPos.y
  443. + (targetVel.y) * estimateTime
  444. + 0.5 * predictedTargetAcceleration.y * estimateTime * estimateTime
  445.  
  446. local estimateZ = targetPos.z
  447. + (targetVel.z - shipVelocity.z) * estimateTime
  448. + 0.5 * predictedTargetAcceleration.z * estimateTime * estimateTime
  449.  
  450. -- Recalculate distance after initial estimate
  451. dx = estimateX - sourceX
  452. dy = estimateY - sourceY
  453. dz = estimateZ - sourceZ
  454. distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  455.  
  456. --Refine estimateTime
  457. estimateTime = distance / missileSpeed
  458. estimateTime = math.min(math.max(estimateTime,0.01),8)
  459.  
  460. -- Recompute future position with refined time
  461. estimateX = targetPos.x
  462. + (targetVel.x) * estimateTime
  463. + 0.5 * predictedTargetAcceleration.x * estimateTime * estimateTime
  464.  
  465. estimateY = targetPos.y
  466. + (targetVel.y) * estimateTime
  467. + 0.5 * predictedTargetAcceleration.y * estimateTime * estimateTime
  468.  
  469. estimateZ = targetPos.z
  470. + (targetVel.z) * estimateTime
  471. + 0.5 * predictedTargetAcceleration.z * estimateTime * estimateTime
  472.  
  473. return {x = estimateX, y = estimateY, z = estimateZ}
  474. end
  475.  
  476. local function terminal()
  477. local now = os.clock()
  478. dt = now - lastTime
  479. lastTime = now
  480. if dt <= 0 then dt = 0.001 end
  481. --print(textutils.serialize(target))
  482. local results = radar.scanForShips(8000)
  483. pos = ship.getWorldspacePosition()
  484. local yaw = math.deg(getYaw())
  485. if yaw>360 then yaw = yaw - 360 end
  486. missileVelocity = ship.getVelocity()
  487. missileSpeed = math.sqrt(missileVelocity.x ^ 2 + missileVelocity.y ^ 2 + missileVelocity.z ^ 2)
  488. pitch = math.deg(getPitch())
  489.  
  490. local targetSpeed = 0
  491.  
  492.  
  493. if target.type == "ship" then
  494. for i, object in ipairs(results) do
  495. if object.id == lockedId then
  496. -- Update position and targetVel
  497. targetPos = object.pos
  498. targetVel = object.velocity
  499. targetSpeed = math.sqrt(targetVel.x^2 + targetVel.y^2 + targetVel.z^2)
  500. local dx = targetPos.x - pos.x
  501. local dy = targetPos.y - pos.y
  502. local dz = targetPos.z - pos.z
  503. local immediateDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  504.  
  505. -- Calculate LOS unit vector
  506. local losLength = math.sqrt(dx^2 + dy^2 + dz^2)
  507. local losUnit = {
  508. x = dx / losLength,
  509. y = dy / losLength,
  510. z = dz / losLength
  511. }
  512. if missileSpeed < 200 then rateOfChase = 200 else rateOfChase = missileSpeed end
  513. -- Compute rate of escape using dot product
  514. local rateOfEscape = targetVel.x * losUnit.x + targetVel.y * losUnit.y + targetVel.z * losUnit.z
  515. rateOfClosure = rateOfChase - rateOfEscape
  516. rateOfClosure = math.max(math.min(rateOfClosure,400),10)
  517.  
  518. -- Update pitch, yaw, and distance
  519. local estimatePos = predictFuturePosition(targetPos,targetVel,pos.x,pos.y,pos.z,rateOfClosure)
  520.  
  521. local dx = estimatePos.x - pos.x
  522.  
  523. local dy = estimatePos.y - pos.y
  524. local dz = estimatePos.z - pos.z
  525.  
  526. local targetHorizontalDistance = math.sqrt(dx * dx + dz * dz)
  527.  
  528. TargetYaw = math.deg(math.atan2(-dx, dz))
  529. TargetYaw = (TargetYaw + 180) % 360
  530.  
  531. TargetPitch = math.deg(math.atan2(dy, targetHorizontalDistance))
  532.  
  533. yawError = TargetYaw - yaw
  534. pitchError = TargetPitch - (-pitch)
  535. rollError = math.deg(getRoll())
  536. -- Output diagnostics
  537. end
  538. end
  539. elseif target.type == "waypoint" then
  540. -- Update position and targetVel
  541. targetPos = target.pos
  542.  
  543. local dx = targetPos.x - pos.x
  544. local dy = targetPos.y - pos.y
  545. local dz = targetPos.z - pos.z
  546. local immediateDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  547. missileSpeed = math.sqrt(missileVelocity.x^2 + missileVelocity.y^2 + missileVelocity.z^2)
  548. if missileSpeed < 0.1 then missileSpeed = 0.1 end
  549.  
  550. -- Update pitch, yaw, and distance
  551. local estimateTime = immediateDistance/missileSpeed
  552.  
  553. local targetHorizontalDistance = math.sqrt(dx * dx + dz * dz)
  554.  
  555. TargetYaw = math.deg(math.atan2(-dx, dz))
  556. TargetYaw = (TargetYaw + 180) % 360
  557.  
  558. projectedMissileY = pos.y + missileVelocity.y * estimateTime
  559. yLevelDiff = targetPos.y - projectedMissileY
  560. TargetPitch = math.deg(math.atan2(dy, targetHorizontalDistance))
  561.  
  562. yawError = TargetYaw - yaw
  563. pitchError = TargetPitch - (-pitch)
  564. rollError = math.deg(getRoll())
  565.  
  566. end
  567.  
  568. -- Ensure yaw is between -180 and 180 for error
  569. if yawError > 180 then
  570. yawError = yawError - 360
  571. elseif yawError < -180 then
  572. yawError = yawError + 360
  573. end
  574.  
  575. if previousDistance then
  576. deltaDistance = previousDistance - immediateDistance
  577. else
  578. deltaDistance = 0 -- Initialize if this is the first frame
  579. end
  580. previousDistance = immediateDistance
  581.  
  582. -- PID control for yaw
  583. local yawOutput, yawIntegral, yawPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, yawError, yawIntegral, (yawError - yawPrevError), yawPrevError, dt)
  584. yawOutput = -math.min(math.max(yawOutput, -10), 10) / (1+math.abs(rollError)*0.1)
  585.  
  586. -- PID control for pitch
  587. local pitchOutput, pitchIntegral, pitchPrevError = PIDController(Kp_pitch, Ki_pitch, Kd_pitch, pitchError, pitchIntegral, (pitchError - pitchPrevError), pitchPrevError, dt)
  588. pitchOutput = -math.min(math.max(pitchOutput, -10), 10) / (1+math.abs(rollError)*0.1)
  589.  
  590.  
  591. -- PIDcontrol for roll
  592. local rollOutput,rollIntegral,rollPrevError = PIDController(Kp_roll, Ki_roll, Kd_roll, rollError, rollIntegral, (rollError - rollPrevError), rollPrevError, dt)
  593. rollOutput = -math.min(math.max(rollOutput, -10), 10)
  594.  
  595. --yaw and pitch flight control
  596. if yawOutput > 0 then
  597. topFlap.setAngle(yawOutput - rollOutput)
  598. bottomFlap.setAngle(yawOutput + rollOutput)
  599. elseif yawOutput < 0 then
  600. topFlap.setAngle(yawOutput - rollOutput)
  601. bottomFlap.setAngle(yawOutput + rollOutput)
  602. else
  603. topFlap.setAngle(0)
  604. bottomFlap.setAngle(0)
  605. end
  606.  
  607. if pitchOutput > 0.1 then
  608. leftFlap.setAngle(pitchOutput + rollOutput)
  609. rightFlap.setAngle(pitchOutput - rollOutput)
  610. elseif pitchOutput < -0.1 then
  611. leftFlap.setAngle(pitchOutput + rollOutput)
  612. rightFlap.setAngle(pitchOutput - rollOutput)
  613. else
  614. leftFlap.setAngle(0)
  615. rightFlap.setAngle(0)
  616. end
  617.  
  618. print("yawOutput: "..yawOutput)
  619. print("pitchOutput: "..pitchOutput)
  620. print("rollOutput: "..rollOutput)
  621. print("missileSpeed: "..missileSpeed)
  622. print("rate of closure: "..rateOfClosure)
  623. if missileSpeed > fastestSpeed then fastestSpeed = missileSpeed end
  624. print("fastestSpeed: ",fastestSpeed)
  625.  
  626. if missileSpeed < 60 then
  627. print("Speed below optimal, accelerating")
  628. redstone.setAnalogOutput("top",highThrust)
  629. else
  630. if yawOutput > 8 or pitchOutput > 8 or missileSpeed > 240 then
  631. redstone.setAnalogOutput("top",0)
  632. end
  633. end
  634. end
  635.  
  636. local function fuze()
  637. local results = radar.scanForShips(2000)
  638. pos = ship.getWorldspacePosition()
  639. local distance
  640. local missileVelocity = ship.getVelocity()
  641. local missileSpeed = math.sqrt(missileVelocity.x^2 + missileVelocity.y^2 + missileVelocity.z^2)
  642.  
  643. if target.type == "ship" then
  644. for i, object in ipairs(results) do
  645. if object.id == lockedId then
  646. targetPos = object.pos
  647. local dx = targetPos.x - pos.x
  648. local dy = targetPos.y - pos.y
  649. local dz = targetPos.z - pos.z
  650.  
  651. targetSpeed = math.sqrt(targetVel.x^2 + targetVel.y^2 + targetVel.z^2)
  652. distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  653. end
  654. end
  655. elseif target.type == "waypoint" then
  656. local dx = target.pos.x - pos.x
  657. local dy = target.pos.y - pos.y
  658. local dz = target.pos.z - pos.z
  659. distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  660. targetSpeed = 0
  661. end
  662.  
  663. -- **Calculate Rate of Change of Distance Using Delta Time**
  664. local deltaDistance = lastDistance - distance
  665. local rateOfClosure = math.min(deltaDistance / (dt + 0.0001),200)
  666.  
  667. -- **Proximity Fuze Logic**
  668. local timeToHit = distance / (rateOfClosure + 0.0001)
  669.  
  670. if timeToHit < 0.4 and deltaDistance > 0 and distance < 50 then
  671. sleep(math.max(timeToHit - 0.02, 0)) -- Prevent negative sleep time
  672. print("Proximity fuze detonating!")
  673. redstone.setOutput("left", true)
  674. sleep(0.1)
  675.  
  676. -- Reset all outputs
  677. local outputs = {"front", "left", "bottom", "right", "back", "top"}
  678. for _, output in ipairs(outputs) do
  679. redstone.setOutput(output, false)
  680. end
  681.  
  682. print("Fastest speed: " .. missileSpeed)
  683. error("Proximity fuze detonated")
  684. end
  685.  
  686. -- **Impact Fuze Logic**
  687. if redstone.getInput("right") and distance < 70 then
  688. print("Impact fuze detonating!")
  689. redstone.setOutput("left", true)
  690. sleep(0.1)
  691.  
  692. -- Reset all outputs
  693. local outputs = {"front", "left", "bottom", "right", "back", "top"}
  694. for _, output in ipairs(outputs) do
  695. redstone.setOutput(output, false)
  696. end
  697.  
  698. print("Fastest speed: " .. missileSpeed)
  699. error("Impact fuze detonated")
  700. end
  701.  
  702. lastDistance = distance
  703. end
  704.  
  705. parallel.waitForAny(
  706. function()
  707. while true do
  708. local results = radar.scanForShips(4000)
  709. pos = ship.getWorldspacePosition()
  710. local targetSpeed = 0
  711.  
  712. if target.type == "ship" then
  713. for i, object in ipairs(results) do
  714. if object.id == lockedId then
  715. targetPos = object.pos
  716. targetVel = object.velocity
  717. targetSpeed = math.sqrt(targetVel.x^2 + targetVel.y^2 + targetVel.z^2)
  718.  
  719. local dx = targetPos.x - pos.x
  720. local dy = targetPos.y - pos.y
  721. local dz = targetPos.z - pos.z
  722. horizontalDistance = math.sqrt(dx * dx + dz * dz)
  723. end
  724. end
  725. elseif target.type == "waypoint" then
  726. local dx = target.pos.x - pos.x
  727. local dy = target.pos.y - pos.y
  728. local dz = target.pos.z - pos.z
  729. horizontalDistance = math.sqrt(dx * dx + dz * dz)
  730. end
  731.  
  732. -- Check conditions for terminal phase
  733. if horizontalDistance < 200 then
  734. --print("terminal phrase")
  735. parallel.waitForAll(
  736. terminal,
  737. fuze
  738. )
  739. else
  740. --print("initial phrase")
  741. terminal()
  742. end
  743. end
  744. end,
  745. broadCastid
  746. )
  747.  
Advertisement
Add Comment
Please, Sign In to add comment