Place object without overlap others

400 views Asked by At

Im having a problem in one of my projects in unity. I basicly have a system where you click an object and then you click somewhere inside an area and the object goes to that position. the problem is that those objects can't overlap. And they can't use physics. to detect colision with each other. I have been working on this for a long time I got something but still not totally working and I hoped someone could help me.

What im basicly doing is getting all objects near the click and then if there are some just calculate the directions between the click and those objects and then add them to the position that seems to work sometimes they don't overlap other times they do and they go to far away and I need them to be near the click.

code:

public Vector3 GetPossiblePosition(List<GameObject> nearbyDiscs, Vector3 position)
{ 
    float initialY = transform.position.y;
    Vector3 idealPosition = position;
    List<Vector3> directions = new List<Vector3>();

    if(nearbyDiscs.Count > 0)
    {
        foreach (GameObject disc in nearbyDiscs)
        {
            Vector3 newDirection = position - disc.transform.position;
            directions.Add(newDirection);
        }

        for (int i = 0; i < directions.Count; i++)
        {
            idealPosition += directions[i] / directions.Count;
            List<GameObject> discs = CheckForNearbyDiscs(idealPosition);
            if (discs.Count < 1)
                break;
        }
    }
    idealPosition.y = initialY;
    return idealPosition;
}

behaviour:

enter image description here

1

There are 1 answers

0
Nishchhal Bakshi On

You can easily do this using Physics2D.OverlapCircleAll

public static Collider2D[] OverlapCircleAll(Vector2 point, float radius, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);

this method returns an array of colliders, you can simply check overlapping if the length of the returning array is greater than one and can handle accordingly.