Search code examples
c#unity-game-enginesliding

Unity third person Character Controller buggy


I just finished watching this:

Youtube - third person controller

Tutorial for third person controller. But after programming the scripts I have two bugs:

My character keeps "sliding" across the floor even when I stop pressing w. You can imagine it like on an ice rink.

Although I have inserted a rigidbody,but the character does not fall to the ground! My slightly modified code from the Video:

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

    public class player : MonoBehaviour
    {
        public Animator playerAnim;
        public Rigidbody playerRigid;
        public float w_speed, wb_speed, olw_speed, rn_speed, ro_speed;
        public bool walking;
        public Transform playerTrans;

        void FixedUpdate()
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                playerRigid.velocity = transform.forward * w_speed * Time.deltaTime;
            }

            if (Input.GetKeyDown(KeyCode.S))
            {
                playerRigid.velocity = -transform.forward * wb_speed * Time.deltaTime;
            }
        }

        void Update()
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                playerAnim.SetTrigger("walk");
                playerAnim.ResetTrigger("idle");
                walking = true;
                //steps1.SetActive(true);
            }
            if (Input.GetKeyUp(KeyCode.W))
            {
                playerAnim.ResetTrigger("walk");
                playerAnim.SetTrigger("idle");
                walking = false;
                //steps1.SetActive(false);
            }
            if (Input.GetKeyDown(KeyCode.S))
            {
                playerAnim.SetTrigger("walk");
                playerAnim.ResetTrigger("idle");
                walking = true;
            }
            if (Input.GetKeyUp(KeyCode.S))
            {
                playerAnim.ResetTrigger("walk");
                playerAnim.SetTrigger("idle");
                walking = false;
            }
            if (Input.GetKey(KeyCode.A))
            {
                playerTrans.Rotate(0, -ro_speed * Time.deltaTime, 0);
            }
            if (Input.GetKey(KeyCode.D))
            {
                playerTrans.Rotate(0, ro_speed * Time.deltaTime, 0);
            }
        }
    }

Solution

  • Did you assign physics material to your rigidbody? If not then go to Assets > Create Physic Material and create a new one. Give it high friction and add it to your rigidbody. More Info here: https://docs.unity3d.com/Manual/class-PhysicMaterial.html