Game Development Reference
In-Depth Information
Arming the Player with a Gun Script
The last thing you will need to do to make the player and zombie able to interact com-
petitively is to add a gun to the player. This script is an excellent general script for guns;
its changeable variables control the mechanics that distinguish one gun from another in
many video games. PlayerWeapons will be a container object for any weapons you add to
the player. It will also manage these weapons and enable the keyboard's number keys to
switch between them with a script.
1. If it is not already open, open your Unity project and current scene.
2. Use the GameObject menu to create an empty. In the Hierarchy view, rename the
new empty PlayerWeapons . Make this object a child of the FPS Controller's camera
object and change its transform coordinates in the upper part of the Inspector view
to 0,0,0. This places it in the exact position of its parent object.
3. In your Scripts folder, create a new JavaScript file called PlayerWeapons.js .
he Update function in this script will check to see if the player is clicking either
the Fire1 input button, which is mapped to the Ctrl key, or LMB by default in Unity.
This script also organizes any child object and enables them to be switched with the
number keys.
4. Open this script and enter the following code:
var NoSafety : boolean = true;
function Start () {
SelectWeapon(0);
}
function Update () {
if (Input.GetButton (“Fire1”) && NoSafety)
BroadcastMessage(“Fire”);
if (Input.GetKeyDown(“1”)) {
SelectWeapon(0);
}
else if (Input.GetKeyDown(“2”)) {
SelectWeapon(1);
}
}
function SelectWeapon (index : int) {
for (var i=0;i<transform.childCount;i++) {
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
Search WWH ::




Custom Search