Hallo Leute,
ich versuche grad einen Typischen Auswahlrahmen hinzubekommen wie man ihn aus diversen RTS spielen her kennt, um eine Anzahl an Einheiten auszuwählen.
Der Rahmen wird wie üblich mit gedrückter Maustaste gezogen. Das Funktioniert auch.
Allerdings werden die im Rahmen befindlichen Einheiten nicht Korrekt erkannt.
hier mal der Code:
public class SelectBox : MonoBehaviour
{
private Vector2 _rectStartPos;
private bool _isSelecting = false;
private bool _isMouseDown = false;
private GameManager _manager;
private Rect _rect;
void Awake()
{
_manager = GetComponent<GameManager>();
}
void Update()
{
if (Input.GetAxis("LeftClick") > 0)
{
if (!_isMouseDown)
{
_isMouseDown = true;
_rectStartPos = Input.mousePosition;
}
if (!_isSelecting)
{
if (Vector2.Distance(_rectStartPos, Input.mousePosition) > 1)
_isSelecting = true;
}
}
else if (_isSelecting)
{
_isMouseDown = _isSelecting = false;
_manager.CheckSelectableUnits(_rect);
_rect = new Rect();
}
else
_isMouseDown = false;
}
void OnGUI()
{
if (_isSelecting)
{
// Find the corner of the box
Vector2 origin;
origin.x = Mathf.Min(_rectStartPos.x, Input.mousePosition.x);
// GUI and mouse coordinates are the opposite way around.
origin.y = Mathf.Max(_rectStartPos.y, Input.mousePosition.y);
origin.y = Screen.height - origin.y;
//Compute size of box
Vector2 size = _rectStartPos - (Vector2)Input.mousePosition;
size.x = Mathf.Abs(size.x);
size.y = Mathf.Abs(size.y);
// Draw it!
_rect = new Rect(origin.x, origin.y, size.x, size.y);
GUI.Box(_rect, "");
}
}
}
public class GameManager : MonoBehaviour {
public List<Transform> units = new List<Transform>();
public void CheckSelectableUnits(Rect selectionRect)
{
foreach (Transform unit in units)
{
if (selectionRect.Contains(Camera.main.WorldToScreenPoint(unit.transform.position)))
{
Debug.Log("JOOOOOOOOO");
}
}
}
}