The question is answered, right answer was accepted
Random position, overlap problem.
Hello guys, i im trying to random position of 3 targets so they dont overlap, but sometimes they overlap i dont know why. Im randoming position then looking if distance to some targets is less than 100, than i loop again, but something goes wrong i dont know what.
void Start () {
targets = GameObject.FindGameObjectsWithTag("Target");
SetTargetsPositions();
}
private void SetTargetsPositions()
{
for (int i = 0; i < targets.Length; i++)
{
RandomPos(targets[i]);
}
}
private void RandomPos(GameObject target)
{
Vector2 randomPosition;
randomPosition = new Vector2(Random.Range(-285, 285), Random.Range(336, -262));
for (int i = 0; i < GetTargetList(target).Count; i++)
{
if (Vector2.Distance(randomPosition, GetTargetList(target)[i].GetComponent<RectTransform>().anchoredPosition) < 100)
{
randomPosition = new Vector2(Random.Range(-285, 285), Random.Range(336, -262));
i = 0;
}
}
target.GetComponent<RectTransform>().anchoredPosition = randomPosition;
}
private List<GameObject> GetTargetList(GameObject target)
{
List<GameObject> sortedTargets = new List<GameObject>();
for (int i = 0; i < targets.Length; i++)
{
if (targets[i] != target)
sortedTargets.Add(targets[i]);
}
return sortedTargets;
}
Answer by UnityCoach · Dec 05, 2016 at 01:24 PM
Well, first of all, what you want to do isn't "simple", it is with only three targets, but should you have 10, you may loop for a while until you find an "empty spot".
This is what I understand :
for every target
1/ you get a random position
2/ check it against every other targets
3/ if it's too close to one, you restart the loop
So what happens is that it loops to find a position for the first one, then the second and the third. When it reaches the third, it can't reposition the first, it has to find a spot, which may not be possible.
I would take a different approach, splitting the area in as many sub areas as there are targets, then find a random position for each in that sub area.
$$anonymous$$aybe you right, if i had 10 or more sprites, that would be better, but my problem was that i wanted for loop to reset if random position was incorrect, i used i = 0, but i forgot that i is i++, so i had not i = 0, but i = 1 and this cause an issue. But thanks for idead i will remember it for future.
Follow this Question
Related Questions
Game Object doesn't instantiate at Mouse Position 3 Answers
Changing Player Position when hit by collider 0 Answers
Help with Unity Networking and teleporting player 0 Answers
Trying to Generate Different Random Values for Position of Game Object Instances [C#] 1 Answer
position the player on the same position as an object 0 Answers