Page 1 of 1

Binding two objects

Posted: Mon Apr 16, 2018 9:24 pm
by Lirija
I'm sorry that i did't found a better way to explain this:
i'd like to have some objects work "in tandem" such as a switch that when triggered opens a particular gate or two tiles that teleport the player from one to another, do you have any suggestion on how i can accomplish this?

Re: Make two objects "work together"

Posted: Tue Apr 17, 2018 1:02 am
by Beelz
I think you're overthinking this... Start with the doors:

Code: Select all

function newDoor(x, y)
	return {
		x = x or 0,
		y = y or 0,
		closed = true,

		interact = function() closed = not closed end
	}
end

-- Then you can place them, for simplicity we'll pretend x and y are tile locations
local doors = {}

for i = 1, 10 do
	table.insert(doors, newDoor(math.random(1, 10), math.random(1, 10)))
end
Then make the triggers for the player to step on.

Code: Select all

function newTrigger(x, y, door)
	return {
		x = x or 0,
		y = y or 0,
		door = door or nil,

		interact = function() 
			if door then door:interact() end
		end
	}
end

local triggers = {}

for i = 1, 3 do
	table.insert(triggers, newTrigger(math.random(1, 10), math.random(1, 10), doors[math.random(1, #doors)])
end
Whenever the player moves loop over the list of triggers to see if they're on one. If they are, invoke the interaction.

Code: Select all

for i, v ipairs(triggers) do
	if player.x == v.x and player.y == v.y then 
		v.interact()
		return
	end
end

Re: Make two objects "work together"

Posted: Tue Apr 17, 2018 11:30 am
by Lirija
Thank you! Your explanation was crystal clear!
Just another question: if i want to place the interacting objects using tiled and i have more than one pair in the same map how could i bind them correctly? (the only thing i can think of is give them a name like "object door 1" and using string patterns methods later to assign the door to the corresponding switch)

Re: Binding two objects

Posted: Tue Apr 17, 2018 1:02 pm
by Beelz
Maybe someone else can be more help here... I haven't used Tiled much other than a making static map. The code I provided won't throw an error if the player steps on a trigger that isn't connected to a door. The trick is to pass the door reference to the trigger, then the trigger interacts with the specific door directly. One way or another Tiled won't be able to do everything, and you'll have to link them together eventually. Then again take this with a grain of salt, because as I said, I'm not very experienced with Tiled.