Game Development Reference
In-Depth Information
Listing 4.16 Code to Instantiate an Object and Shoot It from
Another Game Object
var cannonball:GameObject;
function Update ()
{
...
if (Input.GetKey ("left"))
{
this.transform.RotateAround (this.transform.position,
this.transform.forward, 20 * Time.deltaTime);
}
if(Input.GetKeyDown ("space"))
{
var cannonball:GameObject = Instantiate(cannonball,
this.transform.position, this.transform.
rotation);
cannonball.rigidbody.AddForce(this.transform.
up * 10000);
}
}
Step 7. Save the code. Select Cannon in the Hierarchy; in the
Inspector, set the aim script component's Cannonball variable
to the prefab just created.
Step 8. Play. Press the space bar to shoot cannonballs from the
cannon. Modify the value of 10000 in the aim.js script if you want
to see the effects of adding more or less force to the balls.
Step 9. On the terrain opposite the cannon is a flat area. Create a
cube and place it on the flat area. Ensure that you switch between
top and side views to get it in the correct location. Coordinates near
(1758,134,953) are good.
Step 10. Add a rigidbody to the cube.
Step 11. Right-click on the cube in the Hierarchy and select Duplicate.
Use the arrow keys in the Scene to move the duplicate cube next to
the original.
Step 12. Continue this process to create your own castle of cubes.
Copy and Paste will have the same effect as Duplicate and make the
building process quicker.
Step 13. Play. Attempt to knock over the cubes with the
cannonballs by changing the direction of the cannon. If the cannon
seems too far away for you, drag and drop the cannon object onto
the Main Camera in the Hierarchy. It will become attached to it.
Move the camera to the desired location in the Scene. The cannon
will move with it.
Search Nedrilad ::




Custom Search