Game Development Reference
In-Depth Information
of Continuous collision detection against other objects using Continuous or Continuous Dynamic
detection and against static Mesh Colliders without rigidbodies, but Discrete collision detection for
everything else. Since Continuous Dynamic also uses Continuous, it can also have a big effect on
performance.
You've seen Constraints used for animation Root Motion and they work the same way here.
Expanding Constraints and checking a Freeze Position axis stops movement along that axis, while
checking a Freeze Rotation axis stops the object from rotating around that axis.
Controlling a Rigidbody with Forces
AddForce() and AddTorque() are the functions you use in scripts to apply forces to a rigidbody.
Torque is a type of force that results in a rotational movement.
In the Project panel, create a new folder and name it Scripts. Select the Scripts folder, then Create
➤ Javascript, then name the script Forces. Drag the script to the Cube game object in the Hierarchy
to attach it. Double-click the script icon in the Project panel to open it in MonoDevelop for editing.
Delete the Start() and Update() functions. Add the following code:
public var aForce : float = 5;
function FixedUpdate () {
rigidbody.AddForce (Vector3.right * aForce);
}
Physics calculations depend on discrete increments of time, so the time-based FixedUpdate()
function is used instead of the frame-rate-based Update() function. Save, then play in the editor.
Notice that as the cube is moving to the right, it is speeding up. This is because the force is applied
with every FixedUpdate() call, which occurs at every fixed frame-rate frame. aForce is a factor that
you can change in the Inspector to get the response to AddForce exactly the way you want it.
Now change the code in FixedUpdate() to the following:
rigidbody.AddTorque (Vector3.right * aForce);
Recall (or check the Scripting Reference) that Vector3.right is shorthand for (1, 0, 0). Now instead
of moving to the right along the x axis, the cube rotates around the x axis, causing it to move
backward.
While that works fine for applying a constant force, what if you would like to control the force during
gameplay? Comment out the FixedUpdate() function and add the following code:
function OnMouseDown () {
rigidbody.AddTorque (Vector3.forward * aForce);
}
Play, and click the stationary cube to start it rotating around its z axis. Remember, with
OnMouseDown() you must click the game object, in this case the cube, for the code to be executed.
Keep clicking and it rotates faster with each click. Exit Play mode.
 
Search WWH ::




Custom Search