# Prevent object from spawning on another object

Hi,

I’m trying to make a simple 2D game. I have a player object and a enemy object. I’m controlling the player with a mouse and when I click on the enemy it will get destroyed and spawn another enemy object on an random position on the screen.

My problem is that sometimes the enemy spawn on the same place where the player object is at the moment. I need some help how I will prevent this from happening.

This is my code for spawn the enemy:

``````public GameObject Enemy;

public void Start () {

//Create a new enemy.
Instantiate(Enemy, SpawnPosition(), Quaternion.identity);

}

//Create enemy position.
Vector2 SpawnPosition(){

float x, y;
x = Random.Range(-2.7f, 2.7f);
y = Random.Range(3.8f, -4.0f);
return new Vector2(x, y);
}
``````

After you select your random x and y locations, have your code measure the distance between the proposed vector2 location and your player’s actual vector2 location. See: Vector2.Distance(a,b) which measures the distance between points – and if they are too close, just have your script select two new random numbers. See also Unity - Scripting API: Vector2.Distance

Thank you about the information on Vector2.Distance.
I have tried but I’m doing something wrong because I can’t get it to work. It still sometimes spawn on the same location as the player. Here is my new code:

``````public GameObject Enemy;
public GameObject Player;

public void Start () {

//Create a new enemy.
Instantiate(Enemy, SpawnPosition(), Quaternion.identity);

}

//Create enemy position.
Vector2 SpawnPosition(){

float x, y;
x = Random.Range(-2.7f, 2.7f);
y = Random.Range(3.8f, -4.0f);

if(Vector2.Distance(Player.transform.position,new Vector2(x, y)) < 7 )
{
x = Random.Range(-2.7f, 2.7f);
y = Random.Range(3.8f, -4.0f);
}
return new Vector2(x, y);
}
``````

Could you show me in my code how to do it?