Creating a Physics Based Character Controller in Unity
The exercise here demonstrates implementing a customized physics controller in Unity.
For moving a 3D object, the required data is as followed.
- Direction
- Velocity
- Gravity
The direction input shall give left or right signal for movement. The velocity input shall accelerate the movement at a certain speed. The gravity input shall mimic real world physics.
So, create a C# script component on the player object and add the following code.
First of all, a proper handle to the character controller object is required and therefore use the Start method to get the handle.
private CharacterController _characterController;void Start()
{
_characterController = GetComponent<CharacterController>();
}
- Direction
- In the Update method, create a private variable for holding the horizontal axis value.
float _horizontalInput = Input.GetAxis("Horizontal");
- Create a vector3 variable named direction to use the input received from the user.
Vector3 _direction = new Vector3(_horizontalInput, 0, 0);
2. Velocity
- Create a private speed variable with a value as per choice.
private int _speed = 5;
- In the Update method, create a vector3 variable for calculating the velocity.
Vector3 _velocity = _direction * _speed;
3. Gravity
- Create a private gravity variable with a value as per choice.
private int _gravity = 1;
- In the Update method, check for the bool value to see whether the player is grounded or in the air.
- If grounded, there can be another act done. If in the air, the velocity vector’s Y value shall be reduced.
if (_characterController.isGrounded == true)
{
}
else
{
_velocity.y -= _gravity;
}
Finally, use all the results to make the player move using the character controller.
_characterController.Move(_velocity * Time.deltaTime);
That should be it :)
Here is the final result.