Game Development Reference
In-Depth Information
The launcher script at its most basic will require a variable to hold a projectile, a means of tracking
user input, and some code to instantiate and push (with physics) a projectile. Let's begin with the
variables. Besides the projectile, you will have a variable to dictate the speed of the push. By having
it exposed to the Inspector, you will be able to fine tune the action at runtime.
5.
Below the class declaration, add the following variables:
public GameObject projectile; // the projectile prefab
public float speed = 20f; // give speed a default of 20
In the Update function, add the following to get the player input:
6.
// if the Fire1 button (default is left ctrl) is pressed ...
if (Input.GetButton ("Fire1")) {
ShootProjectile(); // ...shoot the projectile
}
You can open the Input manager from Edit, Project Settings, to see what keys belong to the virtual
“Fire1” key. On a Windows machine, it is the left mouse button, “mouse 0” and the “left ctrl” keys.
Next you will create the function that instantiates and fires the projectile.
Create the following function below the Update function:
7.
void ShootProjectile () {
// create a clone of the projectile at the location & orientation of the script's
parent
GameObject potato = (GameObject) Instantiate (projectile, transform.position,
transform.rotation);
// add some force to send the projectile off in its forward direction
potato.rigidbody.velocity = transform.TransformDirection(new Vector3 (0,0,speed));
}
The last line gives the object a push via its rigidbody component. It gets the direction from the
script's object's transform using TransformDirection() . The Vector3 argument says no velocity
in the x or y direction, but a velocity of speed in the z direction. The projectile is instantiated at the
position and orientation of the object that will hold the script.
8. Save the script.
The script will go on either the weapon or an empty gameObject parented to it. With imported assets, the
weapon may not always point in the z direction (forward in Unity). By creating an empty gameObject to
hold the script, you can control both the forward direction and the actual point of instantiation.
1.
Hold the Alt key down, and click on the Gnomatic Garden Defender to expand
its hierarchy.
2.
Select the Bazooka Arm, and focus the viewport to it.
3.
From the GameObject menu, select Create Empty.
4.
Name it Fire Point .
5.
Set the coordinate system to Local so you can see the object's z direction.
 
Search WWH ::




Custom Search