- Home /
Math, place object without overlap others
Hello,
I am having a problem with positioning objects when I move them sometimes point that the user chooses has other object nearby so what I decrease the direction between the point I wanted to put the object and the object that was already there. But now when i have multiple of them it doesn't work well and I don't know what math could I use to figure out the closest point to the click in this case.
Examples of the current behaviour
code:
idealPosition -= directions[0] / 2;
I already tried to to a loop and apply multiple directions but the object is placed far away and I want the closest position.
There is no neat mathematical solution to this as far as I am aware, a heuristic approach is laid out in this question/answer but it is not guaranteed to be the nearest.
You need to solve:
whilst $$anonymous$$imizing:
where c_x and c_y are your cursors coordinates and x and y are your final answer.
Answer by MeNowDeal · Mar 29, 2018 at 07:15 PM
If all of the objects are circles anchored at the center, and you don't care about rotation at the end, and you have a reference to the object you want to avoid overlapping, you could use the following:
Transform.LookAt([other object]);
Transform.Rotate(0,0,180);
//point yourself so that when you move forward, you move away from the center of the other object.
Collider2D[] results=new Collider2D[1];
ContactFilter2D contactFilter = new contactFilter2D();
contactFilter=contactFilter.NoFilter();
//Create a bunch of data fields because the person who wrote the OverlapCollider method was probably not in their right mind.
while(GetComponent<Collider2D>().OverlapCollider(contactFilter,results)!=0)
//while you're still touching another circle.
transform.translate(.1f,0,0);