How to prevent Collider from shaking when colliding with another Collider?

Hello!

I’m creating a player controller script for my first person game, and I have a problem. When I move the player and it collides with something, it starts shaking and moves back and forth. I’ve read that this is because of the transform.Translate() function, so I’ve tried placing it in the LateUpdate() function instead of the default Update() function, to make it execute at the same time as the physics code. That makes it a bit better, but it still shakes too much. It works well with the built in CharacterController.Move(), but I want to code the controller myself, so I wonder how I can solve this. I’ve read one possible solution; to use multiple raycasts and check if something is blocking the player before it is being moved, but I don’t really know how I can do that so that it checks “the whole area in front of the player”?

All help is appreciated!

// TheDDestroyer12

FixedUpdate would run your code in the same step as the physics calculation. Collision and translation never is a good idea, because it bypasses the calculations of the physics engine. Instead of translating by a certain amount, set the velocity of the object (if course it needs a rigidbody). It will make the object move by the same amount, but the collision will work fine.
Do that in FixedUpdate().

To expand on the other answer with a code sample, you’d do something like this:

public Vector2 movement = new Vector2();
Rigidbody2D rb2D;

private void Start()
{
    rb2D = GetComponent<Rigidbody2D>();
}

void FixedUpdate()
{
    GetInput();
    MoveCharacter(movement);
}

private void GetInput() {
    
    movement.x = Input.GetAxisRaw("Horizontal");
    movement.y = Input.GetAxisRaw("Vertical");
}

public void MoveCharacter(Vector2 movementVector)
{
    movementVector.Normalize();
    // move the RigidBody2D instead of moving the Transform
    rb2D.velocity = movementVector * movementSpeed;
}