abc123mewot

LaserSentry

Oct 17th, 2023
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.82 KB | None | 0 0
  1. --- This program finds hostile mobs and fires lasers at them, acting like a sentry tower.
  2.  
  3. --- We check that a manipulator exists and wrap it.
  4. local modules = peripheral.find("manipulator")
  5. if not modules then
  6.     error("Cannot find manipulator", 0)
  7. end
  8.  
  9. --- We require an entity sensor to find mobs and a laser to shoot at them. We error if neither exists.
  10. if not modules.hasModule("plethora:laser") then error("Cannot find laser", 0) end
  11. if not modules.hasModule("plethora:sensor") then error("Cannot find entity sensor", 0) end
  12.  
  13. --- We define a function which fires a laser towards an entity. This is a very naive implementation as it does not
  14. --- account for the entity moving between firing and impact. You could use the `motionX`, `motionY` and `motionZ` fields
  15. --- if you wish to add such functionality.
  16. local function fire(entity)
  17.     local x, y, z = entity.x, entity.y, entity.z
  18.     local pitch = -math.atan2(y, math.sqrt(x * x + z * z))
  19.     local yaw = math.atan2(-x, z)
  20.  
  21.     modules.fire(math.deg(yaw), math.deg(pitch), 5)
  22.     sleep(0.2)
  23. end
  24.  
  25. --- We build a lookup of mobs we wish to target, to avoid shooting non-hostile mobs.
  26. local mobNames = { "Creeper", "Zombie", "Skeleton" }
  27. local mobLookup = {}
  28. for i = 1, #mobNames do
  29.     mobLookup[mobNames[i]] = true
  30. end
  31.  
  32. --- We now sense the vicinity and prepare to fire at them.
  33. while true do
  34.     local mobs = modules.sense()
  35.  
  36.     --- First we build up a list of all mobs that we care about.
  37.     local candidates = {}
  38.     for i = 1, #mobs do
  39.         local mob = mobs[i]
  40.         if mobLookup[mob.name] then
  41.             candidates[#candidates + 1] = mob
  42.         end
  43.     end
  44.  
  45.     --- If we've got a mob then choose a random one and fire towards it. Otherwise, delay for a second before
  46.     --- rescanning.
  47.     if #candidates > 0 then
  48.         local mob = candidates[math.random(1, #candidates)]
  49.         fire(mob)
  50.     else
  51.         sleep(1)
  52.     end
  53. end
  54.  
Add Comment
Please, Sign In to add comment