Game Development Reference
In-Depth Information
Listing 4.2 Spawning Objects at Random Intervals
var ball:GameObject;
function Update ()
{
if(Random.Range(0,200) < 1)
{
var sphere : GameObject =
Instantiate(ball, Vector3(0,5,0),
Quaternion.identity);
}
}
Step 15. Attach this script to the camera. With the camera selected in
the Hierarchy, locate the script in the Inspector and set the value for
ball to the ball prefab created previously.
Step 16. Play. At random intervals a ball will be created and fall down
the screen. When it goes out of view it is destroyed. A ball is created
according to a generated random number between 0 and 200. If this
number is less than 1, a ball is instantiated. To increase the interval
between balls, increase the upper range. To have them appear more
quickly, lower the upper range.
Step 17. To have the balls spawn at locations across the entire screen,
modify the spawn.js code to that in Listing 4.3 .
Listing 4.3 Setting a Random Value for the Position
of Game Objects
var ball:GameObject;
function Update ()
{
if(Random.Range(0,200) < 1)
{
var ballStartPosition = new Vector3(Random.Range
( 6,6),8,0);
var sphere : GameObject =
Instantiate(ball, ballStartPosition , Quaternion.
identity);
}
}
Step 18. Play. Because the starting x value for each ball is taken
randomly from the range 6,6, balls will appear across the width of
the screen, as this is the range of x values for the beakers. You may
have placed your beakers at different distances depending on the
screen resolution. In this case, increase or decrease the random range
to suit. The starting y position is set to 8. If this is not beyond the top
of your screen, you may want to increase it a little. The balls should
spawn just beyond the player's view.
Search Nedrilad ::




Custom Search