Search code examples
c#unity-game-enginegame-developmentgame-physics

Player is jittering when colliding with a wall


When I move against the wall, the player starts jittering.

using UnityEngine;

public class Movement2 : MonoBehaviour
{
    [Header("Movement")]
    public float Speed = 4f;
    public float jumpPower = 3f;

    private Rigidbody2D rb;
    private GroundCheck gr;

    private float horizontal;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        gr = GetComponent<GroundCheck>();
    }

    private void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        if (gr.grounded == true && Input.GetButtonDown("Jump"))
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpPower);
        }
    }
    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * Speed, rb.velocity.y);
    }
}

this is how the problem looks like: https://imgur.com/a/A32jbxL

I don't know how to fix that.


Solution

  • You cannot update physics on Update like you are doing in line rb.velocity = new Vector2(rb.velocity.x, jumpPower);.

    Move these logics to FixedUpdate and it should work.

    Try this:

    public class Movement2 : MonoBehaviour
    {
        [Header("Movement")]
        public float Speed = 4f;
        public float jumpPower = 3f;
    
        private Rigidbody2D rb;
        private GroundCheck gr;
    
        private float horizontal;
        private bool jumping;
    
        private void Start()
        {
            rb = GetComponent<Rigidbody2D>();
            gr = GetComponent<GroundCheck>();
        }
    
        private void Update()
        {
            if (gr.grounded && Input.GetButtonDown("Jump"))
            {
                jumping = true;
            }
        }
    
        private void FixedUpdate()
        {
            horizontal = Input.GetAxisRaw("Horizontal");
            var velocity = new Vector2(horizontal * Speed, rb.velocity.y);
            if (jumping)
            {
                jumping = false;
                velocity.y = jumpPower;
            }
            rb.velocity = velocity;
        }
    }
    

    Also try not to mix lowercase and uppercase characters:

    public float Speed = 4f;
    public float jumpPower = 3f;