You get the start point and end point but you also want to calculate the height and width.
public class CameraSelections : MonoBehaviour
{
public static Rect selection = new Rect(0, 0, 0, 0);
private Vector3 startClick = -Vector3.one;
public Texture2D selectionHighLight = null;
private void LateUpdate()
{
StartDrag();
}
private void StartDrag()
{
if (Input.GetMouseButtonDown(0))
startClick = Input.mousePosition;
else if (Input.GetMouseButtonUp(0))
startClick = -Vector3.one;
HandleSelectionArea();
}
void HandleSelectionArea()
{
if (Input.GetMouseButton(0))
{
selection = new Rect(startClick.x, Screen.height - startClick.y, Input.mousePosition.x - startClick.x, (Screen.height - Input.mousePosition.y) - (Screen.height - startClick.y));
if (selection.width < 0)
{
selection.x += selection.width;
selection.width = -selection.width;
}
if (selection.height < 0)
{
selection.y += selection.height;
selection.height = -selection.height;
}
}
}
private void OnGUI()
{
if (startClick != -Vector3.one)
GUI.DrawTexture(selection, selectionHighLight);
}
}
then in your player or selectable you can set the Selected bool to true if the selectable is inside the Rect
public class Player : MonoBehaviour
{
public bool Selected=false;
void Update()
{
if (Input.GetMouseButton(0))
{
Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
camPos.y = Screen.height -camPos.y;
//if inside the cameras drag selection area then mark player as selected
Selected = CameraSelections.selection.Contains(camPos);
}
}
}
