using System.
Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavior : MonoBehaviour
public float MoveSpeed = 10f;
public float RotateSpeed = 75f;
private float _vInput;
private float _hInput;
-- Adds a private variable of type Rigidbody that will contain a reference to the capsule's Rigidbody
component.
private Rigidbody _rb;
-- The Start method fires when a script is initialized in a scene, which happens when you click on play,
and should be used any time variables need to be set at the beginning of a class.
void Start()
-- The GetComponent method checks whether the component type we're looking for, in this case,
Rigidbody, exists on the GameObject the script is attached to and returns it.
_rb = GetComponent<Rigidbody>();
void FixedUpdate()
{
-- Creates a new Vector3 variable to store our left and right rotation:
Vector3 rotation = Vector3.up * _hInput;
-- Quaternion.Euler takes a Vector3 parameter and returns a rotation value in Euler angles:
We need a Quaternion value instead of a Vector3 parameter to use the MoveRotation method. This is
just a conversion to the rotation type that Unity prefers.
We multiply by Time.fixedDeltaTime for the same reason we used Time.deltaTime in Update.
Quaternion angleRot = Quaternion.Euler(rotation * Time.fixedDeltaTime);
Calls MovePosition on our _rb component, which takes in a Vector3 parameter and applies force
accordingly:
1
The vector that's used can be broken down as follow
s: the capsule's Transform position in the forward direction, multiplied by the vertical inputs and
Time.fixedDeltaTime.
The Rigidbody component takes care of applying movement force to satisfy our vector parameter.
_rb.MovePosition(this.transform.position + this.transform.forward * _vInput * Time.fixedDeltaTime);
Calls the MoveRotation method on the _rb component, which also takes in a Vector3 parameter and
applies the corresponding forces under the hood:
angleRot already has the horizontal inputs from the keyboard, so all we need to do is multiply the
current Rigidbody rotation by angleRot to get the same left and right rotation.
_rb.MoveRotation(_rb.rotation * angleRot);