Player won't stop moving with character controller

I put I character controller on my player and I have a move script. When I press wasd I can move, but I don’t stop moving after I release it and keep sliding on the ground. Anyone know how to fix this?

Script:

private Vector3 moveDirection = Vector3.zero;

private void Update()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveZ = Input.GetAxisRaw("Vertical");

            moveDirection += transform.forward * moveZ * speed * Time.deltaTime;
            moveDirection += transform.right * moveX * speed * Time.deltaTime;

        moveDirection += Physics.gravity;

        controller.Move(moveDirection * Time.deltaTime);
    }
}

It doesn’t stop moving because you never set moveDirection to zero, you only ever add to it with +=

After your controller.Move line add moveDirection = Vector3.zero;

I don’t know why you are adding Physics.gravity (an acceleration vector) to your movement. Move is a displacement.

The following code will move a gameobject around (assuming it has a character controller component)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestScript : MonoBehaviour
{
    private Vector3 moveDirection = Vector3.zero;
    private float speed = 1000;
    private CharacterController controller;

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

    private void Update()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveZ = Input.GetAxisRaw("Vertical");

        moveDirection += transform.forward * moveZ * speed * Time.deltaTime;
        moveDirection += transform.right * moveX * speed * Time.deltaTime;

        controller.Move(moveDirection * Time.deltaTime);
        moveDirection = Vector3.zero;
    }
}

Edit: Not sure if you mean to, but you are multiplying by Time.deltaTime twice.

2 Likes

This worked. Thanks.

1 Like