trainworld_computercraft/computer/3/pathfinding.lua
2025-05-22 20:51:25 +02:00

113 lines
3.1 KiB
Lua

home = vector.new(-250, 96, 108)
up = vector.new(0,1,0)
south = vector.new(0,0,1)
east = vector.new(1,0,0)
function greedystep(target)
if (target-position):dot(facing) > 0 then
if turtle.forward() then
position = position + facing
elseif position + facing ==target then
return false, "the target is occupied"
else
temp = (target-position):dot(facing:cross(up))
if temp>0 then
turtle.turnRight()
facing = facing:cross(up)
elseif temp<0 then
turtle.turnLeft()
facing = - facing:cross(up)
else
temp = (target-position):dot(up)
if temp>0 then
if turtle.up() then
position = position+up
end
elseif temp<0 then
if turtle.down() then
position = position-up
end
else
error("help me im stuck")
end
end
end
else
--we did not need to move in that direction
temp = (target-position):dot(facing:cross(up))
if temp > 0 then
turtle.turnRight()
facing=facing:cross(up)
elseif temp < 0 then
turtle.turnLeft()
facing=facing:cross(-up)
else
if (target-position):dot(facing) == 0 then
temp = (target-position):dot(up)
if temp == 0 then
return false,"the target has been reached"
else
if temp > 0 then
if turtle.up() then
position:add(up)
else
position.sub(up)
end
end
end
end
end
end
-- print(position,facing)
_G.position = position
_G.facing = facing
return true
end
greedystep = require("pathfinding2").greedystep
function to(target)
print(tostring(target))
while greedystep(target) do
end
end
function returnhome()
to(home)
if facing == south then
turtle.turnRight()
facing=facing:cross(up)
end
if facing == east then
turtle.turnLeft()
facing=facing:cross(-up)
end
if facing == -south then
turtle.turnLeft()
facing=facing:cross(-up)
end
_G.facing = facing
_G.position = position
end
function lookat(target)
print("lookat")
while (position+facing).x ~= target.x
or (position+facing).z ~= target.z do
greedystep(target)
end
print("temp")
temp = target.y-position.y
while target.y > position.y do
turtle.up()
position = position+up
end
while target.y < position.y do
turtle.down()
position = position-up
end
_G.position = position
end
return {to = to,
returnHome=returnhome,
lookat = lookat,
home = home}