How to stop player going through walls?

I’m currently having problem stopping my player from going through walls.

Both the player and walls have a Rigidbody and Collider. I’ve heard problems may happen if the player is kinematic but don’t know how to change my code if the player is.

// Start is called before the first frame update
void Start()
    rb = GetComponent<Rigidbody>();
    Cursor.lockState = CursorLockMode.Locked;

// Update is called once per frame
void Update()
    // Move player forwards & backwards.
    float moveVertical = Input.GetAxis("Vertical");
    Vector3 movement = transform.forward * moveSpeed * moveVertical * Time.fixedDeltaTime;
    rb.MovePosition(rb.position + movement);

    // Turn player left & right.
    float moveHorizontal = Input.GetAxis("Horizontal");
    Vector3 movement1 = transform.right * moveSpeed * moveHorizontal * Time.fixedDeltaTime;
    rb.MovePosition(rb.position + movement1);

    camTurn.x += Input.GetAxis("Mouse X");
    camTurn.y += Input.GetAxis("Mouse Y");
    transform.localRotation = Quaternion.Euler(-camTurn.y, camTurn.x, 0);

Hey there. As a beginner programer i encountered this error Many times and Make sure walls have a MESH collider and the player can receive collision

(For future reference, you can use the </> button in the post editor to paste code into a post)

The 2D and 3D versions of MovePosition have different behaviors. The documentation for Rigidbody2D.MovePosition specifically says that it will check for collision along the path of movement. Rigidbody.MovePosition says that it is designed to move a Kinematic Rigidbody to a position.

Typically, kinematic bodies are not pushed by colliders, so that may be why the object moves through walls.

You may have better luck if you disable “is kinematic” on the player’s Rigidbody and modify the Rigidbody.velocity instead of using MovePosition. It looks like your code already has a concept of speed, so it shouldn’t be much of a change.

float moveVertical = Input.GetAxis("Vertical");
Vector3 verticalVelocity = transform.forward * moveSpeed * moveVertical;

float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 horizontalVelocity = transform.right * moveSpeed * moveHorizontal;

rb.velocity = verticalVelocity + horizontalVelocity;

Whenever you are changing rigidbody parameters directly, I recommend doing these changes in FixedUpdate() instead of Update(). So the code above should probably be moved to FixedUpdate().

Set collision detection on your rigid body to continuous and see if that helps. Now also this depends on how your player movement script works. Some work by applying a rigid body force essentially pushing your character forward to create movement. Others teleport your player slowly forward which can cause issues with colliders as you would be eccentrically teleporting your character inside the collider. Hope this helps!