Sometimes, UI elements require some kind of interaction with the player. This recipe, along with the previous and the following ones, will teach you how to create interactive panels. Furthermore, we will see how to make a panel resizable. For instance, the player will be able to resize the panel by dragging one of its corners. This is useful when the UI is full of panels and windows and we want to let the player choose their dimension to suit his needs. To do this, we will use the Event Trigger (Script) component and develop a script to handle the interaction.
using UnityEngine.UI;
statement at the beginning of the script.Vector2
, respectively, for keeping track of the original mouse position and the original DeltaSize
of RectTransform
when the player begins resizing. The third one is a RectTransform
, so we can get access to the RectTranform
of ResizablePanel
. Therefore, we can write the following lines:Vector2 initialMousePos; Vector2 initialDeltaSize; RectTransform rectTransform;
Start()
function, we assign the RectTransform
component, attached to the same game object of this script, to the rectTransform
variable. We can do this by writing these lines:void Start () { rectTransform = (RectTransform)this.transform; }
onDragBegins()
because in order to resize, we will be dragging ResizeArea
. Here, we just assign the initial start position of the mouse to initialMousePos
and the current deltaSize
to initialDeltaSize
:public void onDragBegins(){ initialMousePos = Input.mousePosition; initialDeltaSize = rectTransform.sizeDelta; }
ResizeArea
; means resizing the panel according to how the player moves the mouse. Therefore, we need to create a function called OnDrag
, which will look like this:public void OnDrag(){ Vector2 temp = (Vector2)initialMousePos - (Vector2)Input.mousePosition; temp = new Vector2 (-temp.x, temp.y); temp += initialDeltaSize; rectTransform.sizeDelta = temp; }
OnDragBegins()
function from our script is called.OnDrag()
function from our script is called.Each time the player drags Resize Area, Event Trigger (Script) calls our script. In particular, two functions are called: the OnDragBegins()
function, in which we initialize our variables, and the OnDrag()
function. In the latter, we first create a temporary variable that stores the difference of initialMousePos
and the current mouse position, Input.mousePosition
. This means the distance between where the player started to drag and the current mouse position. Since in this case the difference between vectors is ambiguous, we need to make an explicit cast. Then, we have to invert the x coordinate of the temporary vector if we want to resize the panel coherently. Finally, after adding the initialDeltaSize
to our new vector, we assign it as the new sizeDelta
of rectTransform
.
18.191.162.51