Game Development Reference
In-Depth Information
Save the script, and in the Unity editor drag it to the Main Camera to attach it. With the Main Camera
selected in the Hierarchy, go to the Project panel and open the Assets ➤ Prefabs folder. Drag the
Rocket prefab to the Projectile property in the Rocket Launcher script component in the Inspector.
Most of this code should be familiar to you in the following breakdown:
(1) public var projectile : GameObject;
The GameObject type reference variable is declared as a public variable, allowing you to access it
from the Inspector for easy dragging and dropping in different prefabs.
(2) public var cameraSpeed : float = 5;
Similarly, the
cameraSpeed
factor is declared as a public variable to be available through the
Inspector.
(3) var horiz : float = Input.GetAxis("Horizontal") * Time.deltaTime * cameraSpeed;
var verti : float = Input.GetAxis("Vertical") * Time.deltaTime * cameraSpeed;
transform.Translate(horiz, verti, 0);
In the
Update()
function, first the player input is processed to determine the new horizontal and
vertical coordinates to move the camera using
transform.Translate
. The z coordinate is held at 0 to
maintain the distance between the main camera as launcher and the target grid.
(4) if(Input.GetButtonUp("Fire1")) {
var projectileInstance : GameObject = Instantiate(projectile, transform.position,
transform.rotation);
Destroy(projectileInstance, 2);
}
Next, the
Update()
function tests to determine if the default Fire1 button has been released and, if
true
, creates an instance (instantiates) of a new projectile game object. It then sets the condition for
the projectile instance to be destroyed after two seconds.
The projectile game object also needs a script. In the Project panel, go back to the Assets ➤ Scripts
folder and select Create ➤ Javascript, then name the new script Projectile. Double-click the script
icon to open it for editing in MonoDevelop. Edit the code to the following:
#pragma strict
public var aForce : float = 500;
private var redColor : Color = Color (1, 0, 0);
private var greenColor : Color = Color (0, 1, 0);
function FixedUpdate () {
rigidbody.AddForce (Vector3.forward * aForce);
}