How do I make my entity load new chunks?
Posted: Fri Sep 08, 2023 12:56 am
So y'know how artillery shells load the chunk they're in? I wanna do that with a custom entity. How might I go about doing that?
www.factorio.com
https://forums.factorio.com/
Code: Select all
DISTANCE = 32 -- side length of 1 chunk
local function chart_area(entity)
if not (entity and entity.valid) then return end
local half_size = DISTANCE/2
local pos = entity.position
local area = { {pos.x - half_size, pos.y - half_size}, {pos.x + half_size, pos.y + half_size} }
entity.force.chart(entity.surface, area)
end
Code: Select all
require("util)
local on_tick = function(event)
if not (global.entities and next(global.entities)) then
script.on_event(defines.events.on_tick, nil)
return
end
local entity, last_pos
for e, e_data in pairs(global.entities) do
entity, last_pos = e_data.entity, e_data.position
if entity and entity.valid then
if util.distance(entity.position, last_pos) > DISTANCE then
chart_area(entity)
e_data.position = entity.position
end
else
global.entities[e] = nil
end
end
end
local function add_entity(event)
local entity = event.created_entity or -- on_built_entity, on_robot_built_entity
event.entity or -- script_raised_built, script_raised_revive
event.destination -- on_entity_cloned
if entity.name == "YOUR_ENTITY_NAME" then
-- Enable on_tick handler if this is the entity list is empty!
if not next(global.entities) then
script.on_event(defines.events.on_tick, on_tick)
end
-- Add entity to list
global.entities[entity.unit_number] = { ["entity"] = entity, ["position"] = entity.position}
end
end
script.on_init(function()
global.entities = {}
end)
script.on_load(function()
if (global.entities and next(global.entities) then
script.on_event(defines.events.on_tick, on_tick)
end
end)
-- Register handler for events that create entities
local listen_to = {
"on_built_entity", "on_robot_built_entity", "on_entity_cloned",
"script_raised_built", "script_raised_revive"
}
for e, event in pairs(listen_to) do
script.on_event(defines.events[event], add_entity)
end