- Home /
Two specific transform values instead of random int? Even distribution...
Hi community I am in need of a little assistance. I'm relatively new to JS (or any other language for that matter and have hit a snag. I have managed to cobble together a script for objects in my game that dictates what happens when they fall through the world or out of bounds or fall asleep. The problem I'm having is what I want is for the balls to spawn at 2 (or three or four depending on var) points in the level, but only 1 then the next and so forth. It's to evenly distribute balls amongst the players. Seeing as I am not a scripting genius I can't seem to figure it out without your help.
EXAMPLE IMAGE
MY CODE:
#pragma strict
var floorHeight = 0;
var spawnHeight = .03;
function Update ()
{
if(transform.position.y < floorHeight) //if falls through floor transform to int up
{
transform.position.y = spawnHeight;
}
if(transform.position.y > .5) //above floor .5
{
rigidbody.AddForce (0, -30, 0); // accelerate its speed down
}
if(rigidbody.IsSleeping()) //if at rest transform location to position
{
transform.position = Vector3(Random.Range(4, 7), 1.6, 6.7);
}
//This line of code is to add random movement to ball if sleeping
// if(rigidbody.IsSleeping())
// {
// rigidbody.velocity = Vector3(Random.Range(-5.0, 5.0), 0.01, Random.Range(-5.0, 5.0));
// }
}
Answer by AntiLunchBox · Jun 17, 2013 at 04:01 PM
You can make an array of spawn points and loop through those everytime you spawn an object.
So,
var spawnPoints: Transform[]; //populate this with your spawn points
var currentIndex = 0;
function SpawnBall()
{
if(spawnPoints.Length == 0)
return;
if(currentIndex >= spawnPoints.Length)
currentIndex = 0;
GameObject.Instantiate(ballPrefab, spawnPoints[currendIndex], Quaternion.identity);
currentIndex++;
}
Excuse my javascript, I always use c#, but it should atleast get you in the right direction
Or if you want something more literal to paste into your code, just alternate between points by replacing this line with:
transform.position = Vector3(4+(Random.Range(0, 1)*3), 1.6, 6.7);
tried your idea Antilunchbox but it just seemed to drop everything from the same point.
oh sorry it's:
transform.position = Vector3(4+(Random.Range(0, 2)*3), 1.6, 6.7);
The second parameter is a maximum and is excluded. so that will include 0 and 1
Sorry went to work for 3pm It almost worked consistently but occasionally would just start spawning on one side upto five balls.
As far as your first idea (the more elegant and longer coded one) I can't use it. The game has a set amount of balls and your script would spawn them, i'm just looking to move ones that have fallen through or gotten stuck, evenly amongst the players.
For the time being I'll use the snippet code which is usefull thanks.