Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- note, when first placing the turtle, make sure he's facing south
- local loc = {}
- loc = {
- x = 0,
- y = 0,
- z = 0,
- facing = 0,
- facingToAxis = {
- [0] = { axis = 'z', unit = 1 },
- [1] = { axis = 'x', unit = -1 },
- [2] = { axis = 'z', unit = -1 },
- [3] = { axis = 'x', unit = 1 }
- },
- getAxisForFacing = function()
- return loc.facingToAxis[loc.facing]['axis'], loc.facingToAxis[loc.facing]['unit']
- end,
- turnleft = function()
- loc.facing = (loc.facing - 1) % 4
- turtle.turnLeft()
- end,
- turnright = function()
- loc.facing = (loc.facing + 1) % 4
- turtle.turnRight()
- end,
- turnaround = function()
- loc.turnright()
- loc.turnright()
- end,
- moveforward = function()
- if turtle.forward() then
- local axis, unit = loc.getAxisForFacing()
- loc[axis] = loc[axis] + unit
- return true
- else
- return false
- end
- end,
- face = function(faceto)
- local dirdif = (faceto - loc.facing) % 4
- if dirdif == 1 then
- loc.turnright()
- elseif dirdif == 2 then
- loc.turnaround()
- elseif dirdif == 3 then
- loc.turnleft()
- end
- end,
- movez = function(d)
- if d < 0 then loc.face(2) elseif d > 0 then loc.face(0) end
- return loc.moveforward()
- end,
- movex = function(d)
- if d < 0 then loc.face(1) elseif d > 0 then loc.face(3) end
- return loc.moveforward()
- end,
- movey = function(d)
- if d < 0 then
- return loc.movedown()
- else
- return loc.moveup()
- end
- end,
- moveup = function()
- if turtle.up() then
- loc.y = loc.y + 1
- end
- return false
- end,
- movedown = function()
- if turtle.down() then
- loc.y = loc.y - 1
- end
- return false
- end,
- distanceto = function(x, y, z)
- return math.abs(x) + math.abs(y) + math.abs(z)
- end,
- distancetopos = function(pos)
- return loc.distanceto(pos.X, pos.Y, pos.Z)
- end,
- sortpos = function(a, b)
- return math.abs(a.pos) > math.abs(b.pos)
- end,
- headtowards = function (x, y, z)
- local d = {
- { axis = 'x', pos = x },
- { axis = 'y', pos = y },
- { axis = 'z', pos = z }
- }
- table.sort(d, loc.sortpos)
- for k, v in ipairs(d) do
- print('move'..v.axis)
- if loc['move'..v.axis](v.pos) then
- break
- end
- end
- end
- }
- os.loadAPI("ocs/apis/sensor")
- local sensor = sensor.wrap("right")
- while true do
- local targets = sensor.getTargets()
- local closest
- local closestDistance = 10000000
- for k, btarget in pairs(targets) do
- local dist = loc.distancetopos(btarget.Position)
- if dist < closestDistance and btarget.type == "Player" then
- closestDistance = dist
- closest = btarget
- end
- end
- if closest ~= nil then
- loc.headtowards(closest.Position.X, closest.Position.Y, closest.Position.Z)
- else
- sleep(0.1)
- end
- print(closestDistance)
- if closestDistance < 4 then
- turtle.attack()
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement