Game Development Reference
In-Depth Information
Select the Cube game object in the Hierarchy. Change its Transform position to (0, 1, 0). Now
create a Sphere game object with a Transform position of (0, 2, 0). In the Inspector, select Add
Component ➤ Physics ➤ Rigidbody to add a Rigidbody component. Uncheck Use Gravity. From
the Scripts folder in the Project panel, drag the Forces script to the Sphere in the Hierarchy to add
it; alternatively, select the Sphere in the Hierarchy, then drag the Forces script icon from the Project
panel to the bottom of the Inspector to add it as a component to the Sphere game object. Change
the OnMouseDown() line of code from AddTorque to AddForce :
rigidbody.AddForce (Vector3.forward * aForce);
Save the script. Back in the Inspector view of the editor, change the value of aForce to 1000. Enter
Play mode and click the sphere; it moves forward along the z axis in a straight line. Check Use
Gravity, and now it arcs forward and downward.
What you use only depends on what suits your game. While a magical ball of fire might travel in a
straight line, a rubber chicken launched from a trebuchet should probably respond to gravity. But
what if you'd like your magical ball of fire to accelerate like a rocket? Or your rocket to accelerate like
a rocket?
There are several ways to accomplish this. One is to simply apply the force in FixedUpdate() , where
the force is applied continually rather than once with the click of the mouse.
Another is that the AddForce() function takes a second argument after the Vector3, called ForceMode .
If not explicitly designated, it defaults to Force . If you're reviewing the Unity documentation as
we go, then you may have already found that it also has choices of Acceleration , Impulse , and
VelocityChange . The AddTorque() function also has this second optional ForceMode parameter.
You can make the Sphere accelerate by using AddForce.Acceleration as follows:
rigidbody.AddForce (Vector3.forward * aForce, ForceMode.Acceleration);
Another is not through scripting, but with a handy physics component you can use with rigidbodies
called Constant Force.
First, disable the Sphere's Forces script component by unchecking it in the Inspector. Then select
Add Component ➤ Physics ➤ Constant Force and it will appear in the Inspector (Figure 6-2 ).
Figure 6-2. Constant Force component in the Inspector
The Force and Torque properties define force vectors relative to world space coordinates, while
Relative Force and Relative Torque properties define vectors relative to the object's local space
coordinates. For example, while your player character might run around with a rocket launcher and
point it in any direction, if you set the z coordinate of the Relative Force to a positive value, the
rocket will move forward in the direction that it is pointed. Let's give it a try with a rough prototype.
 
Search WWH ::




Custom Search