character controller in csharp

A Character Controller is used to simulate realistic movement behaviours like jumping, running, walking, and other physics-based movements. Here's an example of setting up a basic character controller in C#:

main.cs
using UnityEngine;

public class CharacterControllerExample : MonoBehaviour
{
    private CharacterController _controller;
    private Vector3 _movement = Vector3.zero;
    private float _speed = 3f;

    private void Start()
    {
        _controller = GetComponent<CharacterController>();
    }

    private void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        _movement.x = horizontal * _speed;
        _movement.z = vertical * _speed;
        _movement.y = 0;

        _movement = transform.TransformDirection(_movement);

        _controller.Move(_movement * Time.deltaTime);
    }
}
672 chars
27 lines

Explanation:

  • We start by creating a class named CharacterControllerExample and inheriting from MonoBehaviour.

  • We create references to the CharacterController component, a Vector3 variable to store the movement of our character, and a float variable to control the speed of our character.

  • In the Start() method, we initialize our character controller component.

  • In the Update() method, we get the horizontal and vertical input from the user, and store the values in our movement vector. We then set our Y value to zero, keeping our character on the same plane.

  • We then call TransformDirection to transform our movement vector to the direction our character is facing.

  • Finally, we call the Move method of our CharacterController component, and pass in our transformed movement vector multiplied by Time.deltaTime, which ensures smooth and consistent movement over time.

Note: Remember to attach this script to the game object having a CharacterController component, and also set the gravity and slope limit according to your preference.

related categories

gistlibby LogSnag