0
\$\begingroup\$

I'm making a puzzle game and can't find ANY solution on how to glue parts so I can move them together as a unit. :(

  1. I tried to making them depend like parent and a child, but when I touch the child, the parent doesn't move or rotate.

  2. I tried to make a List<>() in each part but it didn't work as well. Too much code and resources needed.

\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Attach all objects with one common "Root" object

From what I understand, you want to connect objects together so that they can act like one object and be moved around. Here's a way to do this:

  • Each object has a parent variable (similar to what you already tried). If that variable is empty, the object has no parent.
  • If object a and object b are about to be attached together, decide which one of them should be the parent. Let's assume for this example we want object a to become the parent.
  • Make object b's parent variable point to object a.
  • Whenever the user is about to move, rotate or otherwise transform an object, search recursively through the object's parent value, until you find an object with no parent value (the root object).
  • Transform that root object, as their transformations should affect all children, making it look like they all move as one object.

Example

Let's say we have objects a, b (with a as the parent) and c (with b as the parent).

  • If you are about to move a, do it as normal, and it should affect all children.
  • If you are about to move b, check its parent which is a, which doesn't have a parent (it's the root object) so move that.
  • Similarly if you are about to move c, check its parent which is b, whose parent is a, which doesn't have a parent, so move a again.
\$\endgroup\$
3
  • 1
    \$\begingroup\$ OMG, it's genious! I will try it out. Thanks a lot! \$\endgroup\$
    – Dead Lord
    May 18, 2023 at 10:45
  • \$\begingroup\$ If you need to glue a lot of elements together and do not care which object got glued when in order, you can have them all on the same level below the parent. That way you don't need to go by recursion each time to find the top, the top is always one step up \$\endgroup\$
    – Zibelas
    May 18, 2023 at 11:26
  • \$\begingroup\$ @Zibelas That's definitely an option, but an advantage of recursion is that you can have two separate objects that each has its own children, and attach them together in a common root object. I guess that's also possible to do in the scenario you described, but might require extra work. \$\endgroup\$ May 18, 2023 at 12:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .