How to stop player jiggle when running in to a object 2d

Hi!
Im having a problem with my character controller, When i walk in to a object it jiggle in to the object and back really fast. I couldent find a tutorial first and when i finally did it dident work. I am using a rigidbody and a capsual collider, The rigidbody is set to interpolet and continues.

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

public class PlayerMovement : MonoBehaviour
{
    public float movementSpeed;
    public float jumpForce;
    public float fallSpeed;
    private bool Grounded;
    Vector2 gravity;
    public Rigidbody2D rb;
    // Start is called before the first frame update
    void Start()
    {
        gravity = new Vector2(0, -Physics2D.gravity.y);
    }

    // Update is called once per frame
    void Update()
    {
        JumpFunction();
      
    }

    public void FixedUpdate()
    {
        var movement = Input.GetAxis("Horizontal");
        transform.position += new Vector3(movement, 0, 0) * movementSpeed * Time.deltaTime;
    }
   
    void JumpFunction()
    {
        if(Input.GetKeyDown(KeyCode.Space) && Grounded == true)
        {
            rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }
        if(rb.velocity.y < 0)
        {
            rb.velocity -= gravity * fallSpeed * Time.deltaTime;
        }
    }
   
   
    void OnCollisionEnter2D(Collision2D other)
    {
        if(other.gameObject.CompareTag("Ground"))
        {
            Grounded = true;
           
        }
    }

    void OnCollisionExit2D(Collision2D other)
    {
        if(other.gameObject.CompareTag("Ground"))
        {
            Grounded = false;
        }
    }
}

Moving via transform.position += means you are teleporting your player around and bypassing/ignoring the physics engine entirely. The solution is to move via your Rigidbody2D instead.

1 Like

Okay so i should use addforce but can i use horizontal or do i need to manuely make the keybinds?

With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.

Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.

With a wheel collider, use the motor or brake torque to effect motion.

Do not mix setting position with AddForce or setting velocity.

That’s like me telling you “Run that way” but then forcing you to go to a spot in the room, and then pushing on your arm in another direction. It’s three different things. Pick one.

Either:

  • add force

OR

  • set velocity

OR

  • compute position and call MovePosition