I'm currently rewoking my RTS cover system. This should highlight the closest coverspots from my mouse cursor and sent the units to these locations. everything works, but I can't get the closest sport, it always selects the sames ones, regardless to the mouse position.
These cover spots are child objects of the obstacle, that has this script attached.
This is my not working implementation of the idea:
void Update()
{
var dist = Mathf.Abs(transform.position.z - Camera.main.transform.position.z);
var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
mousePos = v3Pos;
}
...
public void getPointDistances()
{
foreach (CoverPosition pos in coverPositions)
{
if (!pos.occupied)
{
pos.distanceToCursor = Vector3.Distance(pos.transform.position, mousePos);
}
}
Array.Sort(coverPositions, delegate (CoverPosition x, CoverPosition y) { return y.distanceToCursor.CompareTo(x.distanceToCursor); });
}
Later, I simply Iterate over the sorted array and make it visisible.
I'm woking on this for hours, but i cannot find, a solution why it always displays the same cover spots.
I hope, someone can find my (possibly stupid) error.
Edit:
I also tried this, but tata returned always the same values, regardless of my mouse positioning:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
mousePos = hit.transform.position;