Spawning random terrain pieces

Hello! I’m trying to set up a random terrain generator. I’m using e2d for the terrain, and what I did was create about 10 pieces using that. I put them all in an array, and I’m using this code to spawn pieces at random from the array.

  var spawned = 0;
    var start : Transform;
    var end : Transform;
    var player : GameObject;
    var ptimer = 0;
    var terrain : Transform[];
    var ttype = 0;
    function Start () {
    ttype = Random.Range(1, terrain.Length);
    }
    
    function Update () {
    if(player == null){
    ptimer ++;
    if(ptimer >= 10){
    player = GameObject.FindGameObjectWithTag("Player");
    }
    }
    
    if(player){
    var pdis1 = Vector3.Distance(player.transform.position, end.position);
    var pdis2 = Vector3.Distance(player.transform.position, start.position);
    if(pdis1 <= 4000){
    if(spawned == 0){
    spawnend();
    spawned = 1;
    
    }
    }
    
    }
    }
    
    
    function spawnend(){
    //yield WaitForSeconds(5.0); 
    var terrainss = Instantiate(terrain[ttype], Vector3(transform.position.x + terrain[ttype].GetChild(0).collider.bounds.size.x, transform.position.y,7), Quaternion.Euler(0,0,0));
    var ts : randomhillspawn = terrainss.GetComponent("randomhillspawn");
    ts.spawned = 0;
    }

The problem I’m facing is that it’ll spawn 5 - 6 different pieces in one location when it shouldn’t. What am I doing wrong here?

Well they are being placed on top of each other because of Vector3(transform.position.x + terrain[ttype].GetChild(0).collider.bounds.size.x, ... sure collider.bounds.size is not the same every time, but they are being instantiated in relatively the same spot.

How do I fix this then?

1 Answer

1

Try placing spawned = 1; before the call to the function spawnend.
It also looks as though you are resetting spawned to 0 at the end of spawnend and have the call for spawnend in the update function. The update function is called every frame so upwards to 60 times in a second. This can have adverse affects.
You should check the time between the last call to spawnend.

declare a variable to store the time value.

var timeLastSpawnEnd = Time.time;

Then change the following code.

	if(player){
	   var pdis1 = Vector3.Distance(player.transform.position, end.position);
	   var pdis2 = Vector3.Distance(player.transform.position, start.position);
	   if(pdis1 <= 4000){
	   	if(spawned == 0 && Time.time > timeLastSpawnEnd +1 ){
	       	spawnend();
	           spawned = 1;
	     
	        }
	   }
	     
	 }
}
     
     
function spawnend(){
	//yield WaitForSeconds(5.0); 
	var terrainss = Instantiate(terrain[ttype], Vector3(transform.position.x + terrain[ttype].GetChild(0).collider.bounds.size.x, transform.position.y,7), Quaternion.Euler(0,0,0));
    timeLastSpawnEnd = Time.time;
	var ts : randomhillspawn = terrainss.GetComponent("randomhillspawn");
	ts.spawned = 0;

}

This should allow you to make a call to spawnend only once every second.