# How to determine the minimum distance between objects?

I have 2d simple tutorial game.

The game has several objects.

I would like the objects to change their position each time PLAY is pressed.

The idea is that each time you start the game, they are in a different place- but without each other collision.

The problem is that if there are many objects, their position change is visible.

I.e, if the object is loaded on the second object, you can see how it changes positions.

Is it possible to simply set the minimum distance so that objects just don’t load on other objects?

My script now:

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomRange : MonoBehaviour {

float x;
float y;

Vector2 position;

void Start()
{

x = Random.Range(-4, 4);
y = Random.Range(-4, 4);
position = new Vector2(x, y);
gameObject.transform.position = position;

}
public static class PhysicsEx
{
public static bool CheckBounds2D(Vector2 position, Vector2 boundsSize, int layerMask)
{
Bounds boxBounds = new Bounds(position, boundsSize);

float sqrHalfBoxSize = boxBounds.extents.sqrMagnitude;
float overlapingCircleRadius = Mathf.Sqrt(sqrHalfBoxSize + sqrHalfBoxSize);

foreach (Collider2D otherCollider in hitColliders)
{

if (otherCollider.bounds.Intersects(boxBounds))
return (false);
}
return (true);
}
}
}
``````

Also, someone has given me another script that can work, but it does not work:

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CPlacementManager : MonoBehaviour {

public List<Vector2> Positions { get; private set; }

void StartPlay( )
{
Positions = new List<Vector2>();

for ( int nPlaced = 0 ; nPlaced < numberToPlace; ++nPlaced)
{
bool bPlaced = false;

while( !bPlaced )
{
bPlaced = true;
int nCheck = 0;
Vector2 vNextTry = placementCentre + new Vector2(
Random.Range(-halfBounds.x, halfBounds.x)
, Random.Range(-halfBounds.y, halfBounds.y));

while(bPlaced && nCheck < nPlaced )
{
if ( (Positions[nCheck] - vNextTry).sqrMagnitude < minSqrSeparation )
bPlaced = false;

}

if (bPlaced)
}
}
}

#pragma warning disable 649
[SerializeField] Vector2 halfBounds = new Vector2( 4, 4 );
[SerializeField] Vector2 placementCentre;
[SerializeField] int numberToPlace = 10;
[SerializeField] float minSqrSeparation = 1f;
#pragma warning restore 649
}
``````

Some options:

1. Turn off the renderer at the start of the game while you reposition all your objects.

2. Don’t manually place your objects in the editor, but instead instantiate them at the start of the game.