Would it be possible to get an explanation for this function? This seems to be the most complicated part of code for this section for me, and it would be great to understand it.
private void PositionTooltip()
{
// Required to ensure corners are updated by positioning elements.
Canvas.ForceUpdateCanvases();
var tooltipCorners = new Vector3[4];
tooltip.GetComponent<RectTransform>().GetWorldCorners(tooltipCorners);
var slotCorners = new Vector3[4];
GetComponent<RectTransform>().GetWorldCorners(slotCorners);
bool below = transform.position.y > Screen.height / 2;
bool right = transform.position.x < Screen.width / 2;
int slotCorner = GetCornerIndex(below, right);
int tooltipCorner = GetCornerIndex(!below, !right);
tooltip.transform.position = slotCorners[slotCorner] - tooltipCorners[tooltipCorner] + tooltip.transform.position;
}
so after fiddling around with gizmos for a while, the tooltip is instantiated in the middle of the canvas (its original corner placements are the green cubes + magenta sphere marking selected tooltip corner), and its transform.position is the center of the tooltip prefab.
Then, the slot corner (cyan sphere) and tooltip corner (magenta sphere) are calculated.
to get the final spawn position, subtract the tooltip corner’s vector position (magenta) from the slot corner’s vector position (cyan) to get an offset in vector form.
the “arrow” of this calculated offset would be from the origin of the canvas (bottom left of UI square), to the yellow sphere slightly below and to the right from the origin.
if you add that offset to the tooltip instantiated in the middle of the UI Canvas, you will move it to its current position as seen in the image.
If the TooltipSpawner’s Y position is in the top half of the screen, “below” (read: “move tooltip below the tooltipspawner”) is true.
If the TooltipSpawner’s X position is on the left half of the screen, “right” (“move tooltip to the right hand side of the tooltipspawner”) is true.
Of course, if “right” or “below” are false, they really mean “left” and “above”, respectively.
And then finally, the tooltip corner you want is always the “diagonally opposite” corner of the slot corner you have, which is why you put !below and !right for the second GetCornerIndex.
int slotCorner = GetCornerIndex(below, right);
int tooltipCorner = GetCornerIndex(!below, !right);
That’s not 1/2 bad. Probably the trickiest part is those “below” and “right” variables. At first glance, it seems like we’re doing it backwards, but you figured out what was going on there!