Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

How Do i stop my gravity/velocity from contstantly going up/ make it so when u touch the ground it resets

A topic by BenjisCode created May 13, 2025 Views: 110 Replies: 2
Viewing posts 1 to 4

using System.Data;

using UnityEngine;

public class TestMovementNmr2 : MonoBehaviour

{

    public float walkSpeed = 10f;

    public float currentSpeed;

    public float shiftSpeed = 3f;

    private CharacterController controller;

    Vector3 velocity;

    public float jumpHeight = 3f;

    public float shiftJumpHeight = 1f;

    public float groundCheckDistance = 0.4f;

    public LayerMask groundMask;

    public Transform groundCheck;

    public float gravity = -18f;

    bool isGrounded;

    private void Start()

    {

        controller = GetComponent<CharacterController>();

        currentSpeed = walkSpeed;

    }

    

       private void Update()

    {

        // Ground check

        isGrounded = Physics.CheckSphere(groundCheck.position, groundCheckDistance, groundMask);

        if (isGrounded && velocity.y < 0)

        {

            velocity.y = -2f; // Keeps the player stuck to the ground

        }

        // Movement input

        float X = Input.GetAxis("Horizontal");

        float Z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * X + transform.forward * Z;

        // shift speed

        if (Input.GetKey(KeyCode.LeftShift) && isGrounded)

            currentSpeed = shiftSpeed;

        else

            currentSpeed = walkSpeed;

        controller.Move(move * currentSpeed * Time.deltaTime);

        // Jumping

        if (Input.GetButtonDown("Jump") && isGrounded)

        {

            float jumpMultiplier = Input.GetKey(KeyCode.LeftShift) ? 0.5f : 1f;

            velocity.y = Mathf.Sqrt(jumpHeight * jumpMultiplier * -2f * gravity);

        }

        // Gravity

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);

    }

    }

Moderator moved this topic to General Development
Moderator

(moved to the right category)

(1 edit)

If you are using Unity C# (which it looks like you are), you might consider putting your code in discussions.unity.com rather than here (I am not a moderator, just a friendly user). 

To actually answer your question, you can use Unity's in-built gravity system, which you can access in Project Settings > Physics. This allows you not to build a gravity system from scratch and instead focus on other parts of your game.

Hope this helps!