physics.checkbox

Hi All,

I’m very new to c# but I’m muddling through slowly. I am try to make a game based on the old DeathChase game on the spectrum. Today you would call it an endless runner type of game. Your on a motorbike and you chase other bikes through a forest. Now my problem is this. I am trying to use Physics.CheckBox to check if my trees can spawn without them colliding with other trees. At the moment I am not getting much success as my trees overlap. Is there something wrong with the code or am I missing an element in the Unity Editor. All the trees have a rigidbody and a collider which the trigger is set to false.
cheers in advance of any help.

using UnityEngine;
using System.Collections;

public class HazardSpawner : MonoBehaviour {

public GameObject[] hazards;

public int maxHazardCount = 20;

public int hazardCount = 0;

private Transform thisTransform;

private Vector3 thisColl;

void Start () {
	
	thisTransform = GetComponent<Transform> ();

	thisColl = GetComponent<BoxCollider> ().size;
	 
}

void Update(){
	
	if (hazardCount < maxHazardCount) {
		
		SpawnHazard ();
	}
}

void SpawnHazard(){
	
	float spawnPoint = thisTransform.position.x;

	int hazard = (int)Random.Range (0, hazards.Length);

	Vector3 spawn = new Vector3(Random.Range(spawnPoint + -5.0f, spawnPoint + 5.0f), thisTransform.position.y, Random.Range(thisTransform.position.z, thisTransform.position.z + 10.0f));

	bool isFreeOfObstacle = Physics.CheckBox (thisColl / 2, thisColl);

	if (isFreeOfObstacle) {

		Instantiate (hazards [hazard], spawn, Quaternion.identity);

		hazardCount++;
	}
}

}enter code here

Rather than instantiate the tree then check you could get a random location and then check the closest tree. Tag the Tree prefab (e.g. Tree).

private float closest;
private GameObject[] TreeList;

TreeList = GameObject.FindGameObjectsWithTag("Tree");

closest = 1000f;
foreach (GameObject aTree in TreeList)
{
     float dist = Vector3.distance(spawnPosition, aTree.position);
     if (dist < closest)
          closest = dist;
}

Then work out the minimum safe distance and if closest is less than that you have to pick another location.

That’s coded straight from my head to the page so there may be the odd typo here or there but it might give you a hand getting started.