We're going to add a Rigidbody
Component to apply physics to Player. To stop Player from dropping like a rock, out of view of the camera, we'll check Is Kinematic in the Rigidbody properties to turn off the effect of physics. When any of the play States are active, we'll uncheck Is Kinematic in code to allow physics to affect Player.
The following screenshot shows the code for moving Player using physics forces:
In the Inspector, the values stored in the Mass
, Drag
, and Angular Drag
variables under the Rigidbody properties affect the move ability of Player, just like in real life.
In any play State, Is Kinematic is unchecked allowing physics to work.
An analysis of the code we saw in the preceding code screenshot is as follows:
Note that FixedUpdate()
is being used directly in PlayerControl
instead of being controlled by the State Machine:
Line 7: public floa
t speed = 16.0f;
Line 8: public float rotationSpeed = 0.60f;
Line 27: fl
oat foreAndAft = Input.GetAxis("Ver
tical") * speed;
Input.GetAxis("Vertical")
method detects the pressing of the Up Arrow or Down Arrow keys1
, while the down arrow key returns a value of -1speed
which contains the value 16.0
16
or -16
, is stored in the variable foreAndAft
Line 28: float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
Input.GetAxis("Horizontal")
method detects the right or left arrow keys1
, the left arrow key returns a value of -1
rotationSpeed
which contains the value 0.60
0.60
or -0.60
, is stored in the variable rotation
Line 29: rigidbody.AddRelativeForce (0, 0, foreAndAft);
Rigidbody
class to move Player, the Scripting Reference provides AddForce()
and AddRelativeForce()
for moving objectsAddForce()
makes objects move along the x, y, and z axes of the world, which isn't so good if Player isn't facing the direction where the force is being appliedAddRelativeForce()
makes an object move according to it's own x, y, and z axes, so applying force to the z axis of Player moves it correctlyLine 30: rigidbody.AddTorque (0, rotation, 0);
Line 33: void OnTriggerStay(Collider other)
Line 35: rigidbody.AddForce(Vector3.up * hoverPower);
rigidbody.AddForce(0, hoverPower, 0);
3.137.163.62