Game Development Reference
In-Depth Information
This breaks down as follows:
(1) public var prefab : GameObject;
public var amount : int = 10;
Declare the prefab reference variable of type GameObject, and the amount
variable of type int and assign it a value of 10.
1.
(2) for (var i : int = 0; i < amount; i++)
The for loop will repeat as many times as the value of amount .
2.
(3) var position: Vector3 = Vector3(5, Random.Range(9.0, 11.0),
Random.Range(44, 53));
With each loop, create a position Vector3 type variable and assign it an
x-coordinate value of 5 to position it to the right of the elevated track, a
y-coordinate between 9 and 11 because the surface of the elevated track
is at the y-coordinate of 9 and the player character is 2 units tall, and a
z-coordinate between 44 and 53, the boundaries of this zone.
3.
(4) Instantiate(prefab, position, Quaternion.Euler(0, 0, 90));
4.
Create a new instance of the cannon prefab with the previously generated
position and a rotation of 90 around the z-axis to aim it across the width of
the elevated track.
Save the script. In the Unity editor, create an empty game object from the top menu Game Object ➤
Create Empty. Name the new game object Hazard Setup and attach the RandomCannonPositions
script. Drag the Cannon prefab from the Assets ➤ Prefab folder in the Project panel to the Prefab
property of the RandomCannonPositions script in the Inspector. Now position the Hazard Setup
game object out of the way in the Scene view. Save the scene.
If you playtest now, you'll notice that all the cannons fire at once. To vary the launch frequencies,
find the LaunchProjectile script in the Assets ➤ Scripts folder in the Project panel and open it in
MonoDevelop. Add a Start() function with code that selects a random value for frequency :
#pragma strict
public var projectile : GameObject;
public var force : float = 25;
public var frequency : float = 2.0;
private var nextLaunch : float = 0.0;
function Start () {
frequency = Random.Range(0.5, 2.5);
}
function Update () {
if (Time.time > nextLaunch) {
Search WWH ::




Custom Search