Add gravity to character Controller

Hey guys, devxteme here, I was just wondering, what is the best way to add gravity to a character controller, do I always have to create a vector 3 to handle velocity, please share your opinions

Gravity can be done any way you’d like in a CharacterController. It does have a built-in method for moving that handles gravity itself called SimpleMove, but it is less customizable then Move. What I would do it perform a Physics.SphereCheck to see if the player is on the ground, and if they aren’t, apply a gravity force overtime.

using FlaxEngine;

namespace Game
{
    
    public class Player : Script
    {
        [Serialize, ShowInEditor]
        private float sphereRadius = 2;
        [Serialize, ShowInEditor]
        private Vector3 sphereCheckOffset = new Vector3(0, -100, 0);
        [Serialize, ShowInEditor]
        private LayersMask sphereCheckMask;


        private CharacterController controller;
        private float gravityForce = -981f;
        private Vector3 currentVelocity = Vector3.Zero;

        public override void OnAwake()
        {
            controller = Actor.As<CharacterController>();
        }

        public override void OnFixedUpdate()
        {
            if (Physics.CheckSphere(Actor.Position, sphereRadius, sphereCheckMask))
            {
                // Add a small force to make sure we stay on the ground
                currentVelocity.Y = -200;
            }
            else
            {
                // Accumulate gravity force over time
                currentVelocity.Y += gravityForce * Time.DeltaTime;
            }

            controller.Move(currentVelocity * Time.DeltaTime);
        }
    }
}

This can of course be way more complex, but this is a simple working example.

1 Like