Hi, is there anyone that knows why my selection in bounds not working??? The Rect GUI when dragging have displayed but it won’t select my units
I am using this tutorial: How To Build an RTS Game
and
Here’s the code
public static Texture2D WhiteTexture
{
get
{
if (_whiteTexture == null)
{
_whiteTexture = new Texture2D(1, 1);
_whiteTexture.SetPixel(0, 0, Color.white);
_whiteTexture.Apply();
}
return _whiteTexture;
}
}
public static void DrawScreenRect(Rect rect, Color color)
{
GUI.color = color;
GUI.DrawTexture(rect, WhiteTexture);
}
public static void DrawScreenRectBorder(Rect rect, float thickness, Color color)
{
//Top
DrawScreenRect(new Rect(rect.xMin, rect.yMin, rect.width, thickness), color);
//Bottom
DrawScreenRect(new Rect(rect.xMin, rect.yMax - thickness, rect.width, thickness), color);
//Left
DrawScreenRect(new Rect(rect.xMin, rect.yMin, thickness, rect.height), color);
//Right
DrawScreenRect(new Rect(rect.xMax - thickness, rect.yMin, thickness, rect.height), color);
}
public static Rect GetScreenRect(Vector3 screenPos1, Vector3 screenPos2)
{
screenPos1.y = Screen.height - screenPos1.y;
screenPos2.y = Screen.height - screenPos2.y;
Vector3 bR = Vector3.Max(screenPos1, screenPos2);
Vector3 tL = Vector3.Min(screenPos1, screenPos2);
return Rect.MinMaxRect(tL.x, tL.y, bR.x, bR.y);
}
public static Bounds GetVPBounds(Camera cam, Vector3 screenPos1, Vector3 screenPos2)
{
Vector3 pos1 = cam.ScreenToViewportPoint(screenPos1);
Vector3 pos2 = cam.ScreenToViewportPoint(screenPos2);
Vector3 min = Vector3.Min(pos1, pos2);
Vector3 max = Vector3.Max(pos1, pos2);
min.z = cam.nearClipPlane;
max.z = cam.farClipPlane;
Bounds bounds = new Bounds();
bounds.SetMinMax(min, max);
return bounds;
}
Update()
{
if(Input.GetMouseButtonDown(0))
{
mousePos = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
LayerMask layerHit = hit.transform.gameObject.layer;
switch (layerHit.value)
{
case 9:
if(!selectedUnits.Contains(hit.transform))
SelectUnit(hit.transform);
break;
default:
DeselectUnit();
isDragging = true;
break;
}
}
}
if(Input.GetMouseButtonUp(0))
{
foreach(Transform child in map)
{
if(child.name == "3D Markers")
foreach(Transform units in child)
{
if(IsWithinSelectionBounds(units))
SelectUnit(units);
}
}
isDragging = false;
}
}
private void OnGUI()
{
if (isDragging)
{
Rect rect = GetScreenRect(mousePos, Input.mousePosition);
DrawScreenRect(rect, new Color(0f, 0f, 0f, 0.25f));
DrawScreenRectBorder(rect, 3, Color.blue);
}
}
private bool IsWithinSelectionBounds(Transform tf)
{
if(isDragging)
{
return false;
}
Camera cam = Camera.main;
Bounds vpBounds = GetVPBounds(cam, mousePos, Input.mousePosition);
return vpBounds.Contains(cam.WorldToViewportPoint(tf.position));
}