Selection.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Selection : MonoBehaviour
  5. {
  6. public GameObject BoxSelection;
  7. public List<GameObject> units;
  8. private Vector2 startPos;
  9. private Vector2 endPos;
  10. private Rect rect;
  11. private bool drawRect;
  12. private float startX, startZ, endX, endZ;
  13. private GUIContent cont = new GUIContent();
  14. void Start()
  15. {
  16. units = new List<GameObject>();
  17. }
  18. void Update()
  19. {
  20. }
  21. void OnGUI()
  22. {
  23. //if (GameObject.FindGameObjectWithTag("Setting").GetComponent<sett>().OnSelect == true)
  24. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  25. RaycastHit hit;
  26. if (Physics.Raycast(ray, out hit, 100))
  27. {
  28. if (Input.GetMouseButtonDown(0))
  29. {
  30. startPos = Input.mousePosition;
  31. startX = hit.point.x;
  32. startZ = hit.point.z;
  33. drawRect = true;
  34. }
  35. if (Input.GetMouseButtonUp(0))
  36. drawRect = false;
  37. if (drawRect)
  38. {
  39. endPos = Input.mousePosition;
  40. endX = hit.point.x;
  41. endZ = hit.point.z;
  42. if (startPos == endPos) return;
  43. rect = new Rect(Mathf.Min(endPos.x, startPos.x),
  44. Screen.height - Mathf.Max(endPos.y, startPos.y),
  45. Mathf.Max(endPos.x, startPos.x) - Mathf.Min(endPos.x, startPos.x),
  46. Mathf.Max(endPos.y, startPos.y) - Mathf.Min(endPos.y, startPos.y));
  47. BoxSelection.transform.position = new Vector3((startX + endX) / 2, 0f, (startZ + endZ) / 2);
  48. BoxSelection.transform.localScale = new Vector3(endX - startX, 25, endZ - startZ);
  49. GUI.Box(rect, cont);
  50. }
  51. }
  52. }
  53. }