Question by
skoteskote · Nov 24, 2020 at 11:15 AM ·
c#positionvector3list
Unique list of Vector3's
Trying to make a function that generates a list of unique Vector3's, with a specified minimum distance from each other. Eg no Vector3s that are closer than .3f.
According to some other answers on here this should technically work, but it still gives me some positions whose distance is closer than the tolerance. What am I missing?
public static List<Vector3> UniqueVectorList(this GameObject origin, Vector3 min, Vector3 max, int count, float tolerance)
{
List<Vector3> positions = new List<Vector3>();
if (tolerance > Vector3.Distance(min, max))
{
Debug.Log("Tolerance too great");
return null;
}
for (int i = 0; i < count; i++)
{
Vector3 pos = new Vector3(Random.Range(min.x, max.x), Random.Range(min.y, max.y), Random.Range(min.z, max.z));
foreach (Vector3 vec in positions)
{
while (Vector3.Distance(vec, pos) < tolerance)
{
pos = new Vector3(Random.Range(min.x, max.x), Random.Range(min.y, max.y), Random.Range(min.z, max.z));
}
}
positions.Add(pos);
}
return positions;
}
Comment
Best Answer
Answer by skoteskote · Nov 25, 2020 at 12:56 PM
It works when using a bool for the while loop instead of having the condition directly. Don't ask me why, thought the result should be the same. Here's the code if you need:
public static List<Vector3> UniqueVectorList(this GameObject origin, Vector3 min, Vector3 max, int count, float tolerance)
{
List<Vector3> positions = new List<Vector3>();
if (tolerance > Vector3.Distance(min, max))
{
Debug.Log("Tolerance too great");
return null;
}
for (int i = 0; i < count; i++)
{
Vector3 pos = origin.transform.position + new Vector3(Random.Range(min.x, max.x), Random.Range(min.y, max.y), Random.Range(min.z, max.z));
int c = 0;
while (!isOK(pos, positions, tolerance))
{
pos = origin.transform.position + new Vector3(Random.Range(min.x, max.x), Random.Range(min.y, max.y), Random.Range(min.z, max.z));
c++;
if (c > 1000)
{
Debug.LogError("count is too big");
return null;
}
}
positions.Add(pos);
}
return positions;
}
private static bool isOK(Vector3 pos, List<Vector3> poss, float tol)
{
foreach (Vector3 p in poss)
{
if (Vector3.Distance(p, pos) < tol)
return false;
}
return true;
}