Game Development Reference
In-Depth Information
4. In the SpawnBunnies script, add the following new variable declarations:
public Transform currentZone; // the drop zone
float minX; // variables to hold the object's bounding box location
float maxX;
float minZ;
float maxZ;
Rather than calculate the corner locations manually, you can let Unity do the math in the Start
function. This has the added advantage of being able to clone the zone, move it, or resize it at will.
Add the following in the Start function above the Instantiate line to
calculate the bounds:
5.
minX = currentZone. position.x - currentZone. localScale.x/2;
maxX = currentZone. position.x + currentZone. localScale.x/2;
minZ = currentZone. position.z - currentZone. localScale.z/2;
maxZ = currentZone. position.z + currentZone. localScale.z/2;
Because you defined the currentZone variable as a Transform, you need only add .position instead
of transform.position when accessing its x and z values.
Randomization
To make use of the data, you will use Random.Range() to choose the locations to spawn the varmints.
To set the location, you will construct a new Vector3 to hold the x, y, and z values. For y you will use
1.0 so the prefab can drop and settle.
Change the Instantiate line as follows:
1.
// create a new zombie bunny prefab in the scene
Instantiate(zombieBunny, new Vector3(Random.Range(minX,maxX), 1.0f, Random.
Range(minZ,maxZ)), Quaternion.identity);
Quaternion.identity means that the object will have no rotation, it will be perfectly aligned with the
world or parent axes, which all have rotation values at 0.
When using Random.Range with integers, the max number is exclusive . That means it will not use the
maximum range number when generating. This is useful if you are randomizing anything in an array
where the element numbers start at 0 and the last element number is 1 less than the array Length .
For floats, the maximum number is inclusive . It can be one (or more) of the generated numbers.
One thing to be aware of is that random numbers may occur more than once in a list generated by
Random.Range . In case of the zombie bunnies, dropping them with the physics' rigid body will deal
with any duplicate locations.
Before you test the new additions to the script, you will have to make a change to the zombie bunny
prefab. To drop and settle, the zombie bunny will require a Rigidbody component.
2.
Add a Rigidbody component to the zombie bunny prefab in the Project view.
3.
Save the script.
 
Search WWH ::




Custom Search