Character Controller

Summary

Create a player controller script that moves the player controlled entity with the character controller.

Description

You can attach a Unity character controller component to an entity and then move the entity with the CharacterController.Move method. The following example shows how to use character controller to move in a player controller script.

using System;
using KS.Reactor;

/// <summary>Controller that uses 2 axes to control horizontal movement.</summary>
public class MyController : ksPlayerController
{
    private const float SPEED = 2f;
    private const float JUMP_HEIGHT = 1f;

    private ksVector3 m_velocity = new ksVector3();
    private ksVector3 m_gravity = new ksVector3(0f, -9.81f, 0f);

    /// <summary>Unique non-zero identifier for this player controller class.</summary>
    public override uint Type
    {
        get { return 1; }
    }

    /// <summary>Register all buttons and axes you will be using here.</summary>
    /// <param name="registrar">For registering input.</param>
    public override void RegisterInputs(ksInputRegistrar registrar)
    {
        registrar.RegisterAxes(Axes.X, Axes.Z);
        registrar.RegisterButtons(Buttons.JUMP);
    }

    /// <summary>Called after properties are initialized.</summary>
    public override void Initialize()
    {

    }

    /// <summary>Called during the update cycle.</summary>
    public override void Update()
    {
        if (CharacterController == null)
        {
            ksLog.Warning("Character controller is null.");
            return;
        }

        if (CharacterController.IsGrounded)
        {
            // Stop falling if the character is grounded.
            if (m_velocity.Y < 0)
            {
                m_velocity.Y = 0f;
            }

            // Jump. Jumping is only allowed when the character is grounded.
            if (Input.IsPressed(Buttons.JUMP))
            {
                m_velocity.Y += (float)Math.Sqrt(JUMP_HEIGHT * -3.0f * m_gravity.Y);
            }
        }
        else
        {
            // Apply gravity if the character is in the air.
            m_velocity += m_gravity * Time.Delta;
        }

        ksVector3 direction = new ksVector3(Input.GetAxis(Axes.X), 0f, Input.GetAxis(Axes.Z));
        if (direction != ksVector3.Zero)
        {
            Transform.RotateTo(ksQuaternion.FromDirection(direction)); // Rotate
        }
        m_velocity.X = direction.X * SPEED;
        m_velocity.Z = direction.Z * SPEED;
        CharacterController.Move(m_velocity * Time.Delta); // Move
    }
}