I’m having a little bit of difficulty figuring out how to create an rts-style drag selection box using the new GUI.
I’ve already implemented the selection box functionality using a Rect, and followed this tutorial online to display it using OnGUI in just a few lines (see around 13:54 in the tutorial):
private void OnGUI()
{
if (initialClickPosition != -Vector3.one)
{
GUI.color = new Color(1, 1, 1, 0.25f);
GUI.DrawTexture(selectionRect, selectionImage);
}
}
where selectionRect is the Rect in which units will be selected, and selectionImage is simply a 2x2 white square.
This works no matter which direction you drag in (left to right, right to left, top to bottom, bottom to top). I have code for the selectionRect which accounts for negative width and height.
However, using the new GUI, I’m only able to get an Image to correctly display when dragging from top-left to bottom-right. I can’t figure out how to display the sprite correctly when dragging in the other directions.
I have one Canvas with an Image child that has the same 2x2 white sprite. It works whether I use “Tiled” or “Sliced” (after I sliced it in the sprite editor). I set the “anchoredPosition” variable of the Image’s Rect Transform (called “selectionBox”):
selectionBox.rectTransform.anchoredPosition = new Vector2(Input.mousePosition.x, (Screen.height - Input.mousePosition.y) * -1);
As you can see, I had to convert from screen space to GUI space for the y coordinate, and then multiply by -1 because it is in relation to the anchor, which is in the top left of the screen. I then set the “sizeDelta” variable of the Image’s Rect Transform to my original selectionRect’s width and height every frame:
selectionBox.rectTransform.sizeDelta = new Vector2(selectionRect.width, selectionRect.height);
On release, I set the anchoredPosition and sizeDelta just off screen. As I mentioned above, this works for top-left to bottom-right dragging, but not in other directions. If I drag in other directions, the sprite still shows as if it is being dragged top-left to bottom-right.
I’m looking for the code to be able to get the sprite to align correctly when dragging in the other directions. Anyone know what I’m missing here? After messing around with the sizeDelta, I managed to get the sprite going in the other direction, but it looked like it was turned around, and thus not displaying to the camera. I’d appreciate any help anyone can give.
Thanks in advance.