Mark Gilbert's Blog

Science and technology, served light and fluffy.

Staying on top of things

One of the first things I tackled for the algebra game was the drag-n-drop logic for the equation screen.  The path to that logic was not straightforward at all, and I’ll go into more detail about that in my next post.  One of the first oddities I encountered testing this was that the gameobject I was dragging didn’t always appear on top of everything else.  Sometimes it looked like my operation, for example, was sliding behind its siblings.

On the equation screen, there are two types of things that are draggable – operations:

10

And the terms of the equation, which appear in a UI control CJ dubbed “dominos”:

20

Initially, I found that the operation/domino being dragged would appear behind the operations/dominos to its right, along with several other controls rendered on the page.  After a bit, I realized what was happening.  Unity determines the z-order (depth) of the gameobjects on the screen in the order they appear in the Hierarchy tab.

30

Things that appear higher up in the hierarchy will be rendered visually behind things further down in the hierarchy.  When I populate the list of operations, I add them one after another to the OperationsPanel, which meant that the first one would appear visually behind the second, the second behind the third, and so on.

To solve this, as soon as I start dragging an operation or a domino, I re-parent it to the top-level canvas object, and then I make it the last sibling of the canvas:

this._ParentCanvas = transform.root.gameObject;
this._OperationBeingDragged.transform.SetParent(this._ParentCanvas.transform);
this._OperationBeingDragged.transform.SetAsLastSibling();

Since I can only drag one gameobject at a time, these two steps guarantee that the item being dragged will appear below every other gameobject in the hierachy, which means it will appear visually on top of everything else.  When I drop it onto a new container, I re-parent it to that container, which effectively resets it to the “proper” place in the hierarchy.

Advertisements

September 25, 2017 Posted by | Game - Algebra, Unity | 1 Comment