Game Development Reference
In-Depth Information
Step 14. Create a JavaScript file and call it fire . Add the script
from Listing 2.14 .
Listing 2.14 Instantiating a Game Object and Shooting
It Forward Relative to the Creator
var bulletObject: GameObject;
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
var newBullet: GameObject = Instantiate(bulletObject,
this.transform.position,
this.transform.rotation);
newBullet.rigidbody.AddForce(this.transform.forward *
500);
}
}
Step 15. Save fire.js and attach it to the Main Camera , which is part
of the FPC in the Hierarchy. Select the FPC Main Camera in the
Hierarchy and drag and drop the bullet prefab from the Project
onto the exposed bulletObject variable in the fire.js script as shown
in Figure 2.37 .
Step 16. Save and play. The right mouse button, called “Fire1” in the
script, will instantiate copies of the bullet prefab and add a force with
the same direction as the camera. To change the speed of the bullets,
modify the force multiplier in fire.js .
Note
If an object is moving too fast, Unity can sometimes miss the collision
event and it will go through walls and floors. If this happens, try
slowing the object down or making its collision component bigger.
Also note that Unity will not register collisions between two complex
mesh objects. If you have a mesh object that is not colliding, think of
replacing its collider with a simple sphere or box collider. To do this,
click on the object in the Hierarchy and select a new physics collider
from the main menu.
Search Nedrilad ::




Custom Search