Geek Culture
Published in

Geek Culture

Creating a Physics Based Character Controller in Unity

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>();
}
  1. 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.

--

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Recommended from Medium

Google Cloud’s BigQuery Showcases New Administrative Tools

New Roadmap Update

GraphQL & Python — A Beauty in Simplicity, A Beast in Application

Getting Started With AzureDevOps

Enterprise Resource Planning (ERP): What Is It And Who Needs It?

Practice Examples, Dumps & Tips for CKA & CKAD (Certified Kubernetes Administrator) Exam by CNCF

How to SAML federate your AWS account with G Suite

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Samarth Dhroov

Samarth Dhroov

Work in Progress.

More from Medium

Adding Audio to our Prototype

Creating a Simple Cooldown System In Unity

Ledge Grab System: Part IV

In 6 steps, Add a double jump in Unity