I have a 3d infinite runner car racing type game in which the player is stationary and the background moves. In my game I want to spawn coins randomly over time and the coins has to be spawned very much ahead of the player, and the z axis of the coins get reduced keeping y axis constant and x axis values in a random range of -2 and 2. The coins are spawning correctly but they are spawned in an irregular manner. I created four coin game objects in my scene, I want to spawn the 4 coins in a straight line because then the player can easily collect the coins since they are coming in a straight line to the player. The players motion is only in the x axis from -2 to 2. Now my problem is that the coins are spawned irregularly because of that the coins cannot be collected easily by the player. THis is my code:
function Update()
{
MoveCoin();
}
function MoveCoin()
{
ReleaseCoin();
//CoinsOnRoad is an array containing the current coins which are on the road
//CoinPool is the array of coins
for(var i:int =0;i<CoinsOnRoad.length;i++)
{
var gcoin:GameObject = CoinsOnRoad *as GameObject;*
_ gcoin.transform.position.z-=3speedTime.deltaTime;_
-
if(gcoin.transform.position.z>=-10)*
-
{*
//Do nothing if the coin is on the visible area of the road. If it becomes invisible
//remove the coins from CoinsOnRoad Array and insert the coin back to the CoinPool Array -
}*
-
else*
-
{*
CoinPool.push(gcoin); -
CoinsOnRoad.remove(gcoin);*
-
}*
}
}
function ReleaseCoin()
{
if(CoinPool.length==0)
-
{*
-
}*
-
else*
-
{*
-
var coin:GameObject=CoinPool.shift() as GameObject;*
CoinsOnRoad.push(Instantiate(coin,new Vector3(Random.Range(-2.0,2.0),0.3,30+Random.Range(1,10)),Quaternion .identity));
- }*
}
The coins are spawning correctly but in an irregular order. Can someone please help me out? Thanks in advance…Since I’m new to unity, I didn’t knew whether even my game logic is correct or not. Can some one correct me with the code if I’m wrong some where in my code.