How to make a Game Object follow another Game object?

I’m making a game about picking up boxes and putting them in containers

How can I get the player to pick up and drop the boxes?

Implementing this really depends on your exact game design. Do you want the box to be above the character’s head? Follow behind the player character?

For collisions to detect if your player is near enough a box / facing it you can use the builtin collision system. Or you can use facing vector + distance to see if the player can pick up a box.

For updating the position of the box you can use go.get_world_position() along with go.set_position()

4 Likes

I want the box to follow the character

1 Like

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

The box is following the character, but the scenario is invisible

but the scenario is invisible

Could you rephrase what you mean here?

Ok, the boxes are following, but the tiles are invisible for some reason (sorry for my English, it’s because I’m brazilian)

Most likely the z position of things needs to be changed. The z sorting adjusts the z position of the sprites slightly. So try setting the tiles to a z position behind the sprites but still within the default -1 to 1 range (you can change this with your render script).

1 Like