How to make a Game Object follow another Game object?

There are still many ways to have something follow another thing with the following depend on how you want it to look. Here’s a stand alone example of just following based on max distance allowed. Also includes z sorting.

BoxFollow.zip (6.4 KB)

follow

The code for the box to follow the hero object.

local hero_go = "/char_hero"
local max_distance = 20
local speed = 100

local function update_sorting()
	local position = go.get_position()
	position.z = position.y * -0.0001
	go.set_position(position)
end

local function check_distance(self, dt)
	local position = go.get_position()
	local hero_position = go.get_world_position(hero_go)
	local distance = vmath.length(position - hero_position)
	if distance > max_distance then
		local direction = vmath.normalize(hero_position - position)
		go.set_position(position + direction * speed * dt)
	end
end

function update(self, dt)
	check_distance(self, dt)
	update_sorting()
end
9 Likes