using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Selection : MonoBehaviour
{
    public GameObject BoxSelection;
    public List<GameObject> units;
    private Vector2 startPos;
    private Vector2 endPos;
    private Rect rect;
    private bool drawRect;
    private float startX, startZ, endX, endZ;
    private GUIContent cont = new GUIContent();

    void Start()
    {
        units = new List<GameObject>();
    }

    void Update()
    {

    }

    void OnGUI()
    {
        //if (GameObject.FindGameObjectWithTag("Setting").GetComponent<sett>().OnSelect == true)
      
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 100))
            {
                if (Input.GetMouseButtonDown(0))
                {
                    startPos = Input.mousePosition;
                    startX = hit.point.x;
                    startZ = hit.point.z;
                    drawRect = true;
                }

                if (Input.GetMouseButtonUp(0))
                    drawRect = false;

                if (drawRect)
                {
                    endPos = Input.mousePosition;
                    endX = hit.point.x;
                    endZ = hit.point.z;
                    if (startPos == endPos) return;
                    rect = new Rect(Mathf.Min(endPos.x, startPos.x),
        Screen.height - Mathf.Max(endPos.y, startPos.y),
        Mathf.Max(endPos.x, startPos.x) - Mathf.Min(endPos.x, startPos.x),
        Mathf.Max(endPos.y, startPos.y) - Mathf.Min(endPos.y, startPos.y));
                    BoxSelection.transform.position = new Vector3((startX + endX) / 2, 0f, (startZ + endZ) / 2);
                    BoxSelection.transform.localScale = new Vector3(endX - startX, 25, endZ - startZ);
                    GUI.Box(rect, cont);
                }
            }
        
    }
}
