Search Unity

Player won't stop moving with character controller

Discussion in 'Physics' started by mbeal224, Aug 14, 2020.

  1. mbeal224

    mbeal224

    Joined:
    Jul 31, 2020
    Posts:
    20
    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:

    Code (CSharp):
    1.    
    2. private Vector3 moveDirection = Vector3.zero;
    3.  
    4. private void Update()
    5.     {
    6.         float moveX = Input.GetAxisRaw("Horizontal");
    7.         float moveZ = Input.GetAxisRaw("Vertical");
    8.  
    9.             moveDirection += transform.forward * moveZ * speed * Time.deltaTime;
    10.             moveDirection += transform.right * moveX * speed * Time.deltaTime;
    11.  
    12.         moveDirection += Physics.gravity;
    13.  
    14.         controller.Move(moveDirection * Time.deltaTime);
    15.     }
    16. }
     
  2. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
    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)

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class TestScript : MonoBehaviour
    6. {
    7.     private Vector3 moveDirection = Vector3.zero;
    8.     private float speed = 1000;
    9.     private CharacterController controller;
    10.  
    11.     private void Start()
    12.     {
    13.         controller = GetComponent<CharacterController>();
    14.     }
    15.  
    16.     private void Update()
    17.     {
    18.         float moveX = Input.GetAxisRaw("Horizontal");
    19.         float moveZ = Input.GetAxisRaw("Vertical");
    20.  
    21.         moveDirection += transform.forward * moveZ * speed * Time.deltaTime;
    22.         moveDirection += transform.right * moveX * speed * Time.deltaTime;
    23.  
    24.         controller.Move(moveDirection * Time.deltaTime);
    25.         moveDirection = Vector3.zero;
    26.     }
    27. }
    Edit: Not sure if you mean to, but you are multiplying by Time.deltaTime twice.
     
    BigBoiJoel and mbeal224 like this.
  3. mbeal224

    mbeal224

    Joined:
    Jul 31, 2020
    Posts:
    20
    This worked. Thanks.
     
    AlTheSlacker likes this.