- Home /
 
               Question by 
               Podrix · Apr 01, 2018 at 02:51 AM · 
                charactercontrollercharacter movementcharacter controlling  
              
 
              How do i prevent my Player from sliding when i stop walking?
This is my movement script:
 using System.Collections;
 using UnityEngine;
 
 public class PlayerMovement : MonoBehaviour
 {
     public float speed;
 
     private Rigidbody rb;
 
     void Start()
     {
         rb = GetComponent<Rigidbody>();
         speed = 10f;
     }
 
 
     void Update()
     {
 
         float moveHorizontal = Input.GetAxis("Horizontal");
         float moveVertical = Input.GetAxis("Vertical");
 
         Vector3 movementSide = transform.right * moveHorizontal;
 
         Vector3 movementForward = transform.forward * moveVertical;
 
         rb.AddForce(movementSide * speed);
         rb.AddForce(movementForward * speed);
 
     }
 }
And it takes about half a second for my "Player" to start walking and at first he slowly walks forward and pics up speed after some time. When i stop moving he keeps sliding a bit depending on how much speed he has got.
Someone got a easy fix for this? or maybe a better PlayerController script that is understandable?
               Comment
              
 
               
              Answer by augivision · Apr 02, 2018 at 10:40 AM
  using System.Collections;
  using UnityEngine;
  
  public class PlayerMovement : MonoBehaviour
  {
      public float speed;
      private bool moving;
      private Rigidbody rb;
  
      void Start()
      {
          rb = GetComponent<Rigidbody>();
          speed = 10f;
      }
  
  
      void Update()
      {
          if(Input.GetKey("Horizontal") || Input.GetKey("Vertical"))
          {
              moving = true;
          } else{moving = false;}
          
          if(moving)
          {
              Vector3 movementSide = transform.right * moveHorizontal;
              Vector3 movementForward = transform.forward * moveVertical;
              float moveHorizontal = Input.GetAxis("Horizontal");
              float moveVertical = Input.GetAxis("Vertical");
  
              rb.AddForce(movementSide * speed);
              rb.AddForce(movementForward * speed);
           } else {rb.velocity = Vector3.zero;}
  
      }
  }
I may not have this exactly right, but you want to use rb.velocity = Vector3.zero; to stop your player's movement immediately when you are not moving.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                