I’m working on a random road generator and every n seconds based on the first .js code it moves all the pieces toward the player. The second .js code spawns objects at regular intervals at the specified position every time. Problem is, some gaps appear every now and then. I think it’s something to do with the point the object spawn at isn’t always exactly the same spot because of varying speeds of CPU’s but I’m not sure of the Math to displace it correctly. Anyone know what might be wrong with my code?
MoveScene.js
#pragma strict
var speed = 0.01;
function Start () {
}
function Update () {
var blocks : GameObject[] = GameObject.FindGameObjectsWithTag ("Piece") as GameObject[];
for (var block : GameObject in blocks)
{
block.transform.position.z += Time.deltaTime * speed;
if (block.transform.position.z < -5)
Destroy (block);
}
}
ObjectSpawner.js
#pragma strict
// time variables
private var cubeCount = 0;
private var currentTime:float = 0;
public var spawnRate:float = 1.0;
public var distance:float = 15;
var newObject : Transform;
var newObject1 : Transform;
var newObject2 : Transform;
var newObject3 : Transform;
var newObject4 : Transform;
function Awake () {
// create one piece to start with
CreatePrefab();
// start the timer ticking
TimerTick();
}
function Update () {
}
function CreatePrefab()
{
var pos : Vector3 = new Vector3(0,0,distance);
var choice = Random.Range(0,4);
var obj : Transform;
// tend to paste straights
var straight = Random.Range(0,4);
if (straight <2)
choice =5;
if (choice == 0 || choice ==5)
obj = Instantiate(newObject, pos, transform.rotation);
if (choice == 1)
obj = Instantiate(newObject1, pos, transform.rotation);
if (choice == 2)
obj = Instantiate(newObject2, pos, transform.rotation);
if (choice == 3)
obj = Instantiate(newObject3, pos, transform.rotation);
if (choice == 4)
obj = Instantiate(newObject4, pos, transform.rotation);
Debug.Log("Road piece created");
cubeCount ++;
obj.gameObject.tag = "Piece";
}
function TimerTick()
{
// while there are seconds left
while( currentTime>-1)
{
// increase the time
currentTime++;
CreatePrefab();
// wait for 3 second
yield WaitForSeconds(spawnRate);
}
// otherwise game has ended.
}