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

Indexing & Metadata: How to Deal with Video and Unstructured Data

Using the Datadog API and Puppeteer to Create Timeseries Metric GIFs

Fireside chat with Ali Ghodsi

Docker Compose : Setting up web development stack step by step (Part 5 — Nginx).

Improvabunga: “Done” is Better than “Perfect”

Go Module Decoupling: A Rescue Guide

The Forecast In Project Management.

Packages in salesforce

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

Tessellation in HDRP

Camera Look System in Unity!

Switch Statements To The Rescue!

How to switch between Cinemachine cameras in Unity