Spawning Cars according to the position of Player Car

In my Car Game i have a player car and enemy cars. Initially I Instantiated the cars at some random positions but the issue is, i want, as the terrain moves forward the position of the cars at which they will instantiate moves accordingly with the player car within some radius.

You can use OnBecameVisible Function of mesh renderer of the Enemy Cars whenever they are not visible in the camera after being hit and can reset them again.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void OnBecameInvisible() {

on spawn, use the player position and add a vector to it with random x and z, and y = 0. random -1 to 1 (float) should suffice. normalize that vector and multiply it by the distance you want cars to spawn at from the player.

@mobee555 You have to track the position of the player car and when you instantiate the enemies then you must have to set the position of the enemies according to the player car. Or you can put the spawner empty game object in the car and then set distance accordingly to instantiate the enemy.

It’s not a radius because I’d have to dig how to select a random point in a circle, but doing this in a square-shaped area around the player is fairly straightforward…

float radius = 25f; //The "radius" of your square area here.
float xOffset = Random.Range(-radius, radius);
float zOffset = Random.Range(-radius, radius);
Vector3 playerPosition = player.transform.position;
Vector3 spawnPosition = new Vector3(playerPosition.x + xOffset, playerPosition.y, playerPosition.z +zOffset);

@mobee555 I came up with a solution that might be what you’re looking for. It’s not perfect, you’re still going to have to tell it the rotation of the car that gets spawned, and the Y distance (I’m assuming that you’re not using a level track).

public void RandomSpawn(float minRange, float maxRange, GameObject player, Quaternion carRotation, float carYdistance, params GameObject[] carsToSpawn){

float spawnRads = Mathf.Deg2Rad * Random.Range(0f, 359f);
float spawnDistance = Random.Range(minRange, maxRange);
float x = player.transform.position.x + Mathf.Cos(spawnRads) * spawnDistance;
float z = player.transform.position.z + Mathf.Sin(spawnRads) * spawnDistance;

GameObject.Instantiate<GameObject>(carsToSpawn[Random.Range(0, carsToSpawn.Length)], new Vector3(x, carYdistance, z), carRotation);