Create Joints with array/Table (SOLVED)

Hello everyone! I’m co-developing a game while learning how to use both Defold and Lua.
While I’m having no problems finding answers to most of my issues I find myself stuck trying to make functional chain for an anchor with JOINT_TYPE_HINGE.

So this is the actual item collection, as you can see it has the collision objects and it works as it should.

But my issue is with the code. As you can see below I had to repeat the code a few times and this, I think, it would work fine, it mainly does what it’s supposed to do and also is not too long. But the chain will need to be larger in our project. So my question is: Is there a simpler way to create this Joints? Can I create them with a table or array? My co-worker says I can but I can’t seem to wrap my head around how I could make it work

You can put the links into a table (read: array) and iterate over the entries in the table.

local objects = {"main_anchor", "chain_piece1", "chain_piece2", "chain_piece3" }
for i=2, #objects do
    local joint_id = "chain_link" .. (i - 1)
    local coll_a = objects[i - 1] .. "#anchor_chain_joint_bottom"
    local coll_b = objects[i] ..  "#anchor_chain_joint_top"
    physics.create_joint(physics.JOINT_TYPE_HINGE, coll_a, joint_id, pos_a, coll_b, pos_b)
end

Or you can do it in a for-loop:

for i=1,4 do
    local joint_id = "chain_link" .. i
    local coll_a = "chain_piece" .. i .. "#anchor_chain_joint_bottom"
    local coll_b = "chain_piece" .. (i - 1) .. "#anchor_chain_joint_top"
    physics.create_joint(physics.JOINT_TYPE_HINGE, coll_a, joint_id, pos_a, coll_b, pos_b)
end

In both cases you need to be consistent with naming for it to work.

3 Likes

This does work for the chains! And with some tweaks it can probably work with the anchor too, thank you!

I stand corrected, my edit was wrong. Sorry people!

1 Like