Use the following steps to move and rotate the Rigidbody component:
- Add in the following code to PlayerBehavior underneath the Update method, and then save the file:
// 1
void FixedUpdate()
{
// 2
Vector3 rotation = Vector3.up * hInput;
// 3
Quaternion angleRot = Quaternion.Euler(rotation *
Time.fixedDeltaTime);
// 4
_rb.MovePosition(this.transform.position +
this.transform.forward * vInput * Time.fixedDeltaTime);
// 5
_rb.MoveRotation(_rb.rotation * angleRot);
}
Here's a breakdown of the preceding code:
- Any physics- or Rigidbody-related code always goes inside FixedUpdate, rather than Update or the other MonoBehavior methods:
- FixedUpdate is frame rate independent and is used for all physics code.Â
- Creates a new Vector3 variable to store our left and right rotation:
- Vector3.up * hInput is the same rotation vector we used with the Rotate method in the previous example.
- Quaternion...