Game Development Reference
In-Depth Information
In the Project panel Assets ➤ Scripts folder, create a script named LaunchProjectile. Attach it to the
Launcher game object, then open it in MonoDevelop. Edit the code to the following:
#pragma strict
public var projectile : GameObject;
public var force : float = 25;
public var frequency : float = 2.0;
private var nextLaunch : float = 0.0;
function Update () {
if (Time.time > nextLaunch) {
nextLaunch = Time.time + frequency;
var projectileInstance : GameObject = Instantiate(projectile, transform.position,
transform.rotation);
projectileInstance.rigidbody.AddForce (projectileInstance.transform.forward * force,
ForceMode.Impulse);
Destroy(projectileInstance, 2);
}
}
Save the script. This breaks down as follows:
(1) public var projectile : GameObject;
public var force : float = 25;
public var frequency : float = 2.0;
private var nextLaunch : float = 0.0;
The variable declarations; projectile to hold a reference to a GameObject,
while the float variables force and frequency are for you to fine-tune the
projectile behavior from the Inspector. The float variable nextLaunch tracks
the time between each projectile launch.
1.
(2) if (Time.time > nextLaunch)
Time.time is the number of seconds since the game began. The if
conditional tests to see if the time passed is greater than the calculated time
for the next launch of a projectile. If so,
2.
(3) nextLaunch = Time.time + frequency;
nextLaunch is reset to the currently elapsed game playing time plus the
seconds between each launch designated by the float variable frequency.
3.
(4) var projectileInstance : GameObject = Instantiate(projectile,
transform.position, transform.rotation);
Instantiate a clone of the projectile Prefab game object, at the transform.
position and transform.rotation of the parent Launcher game object this
script is attached to.
4.
Search WWH ::




Custom Search