Unity2D: How to make my player not walk through walls?

Hey, I’m really sorry if this have been answered before, but I tried looking everywhere and I couldn’t really find my solution. (I should also mention I’m extremely new to this, I tried looking through the manual, but I couldn’t quite find what I did wrong :frowning: )

So I’m working on a 2D game where there is a character (a UI image) that’s supposed to not walk into walls (also a UI image).

Here’s the code for the character:

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

public class PlayerController : MonoBehaviour
{

    public float speed;

    void Update()
    {
        float v = Input.GetAxisRaw("Vertical");
        float h = Input.GetAxisRaw("Horizontal");
        Vector3 direction = new Vector3(h, v, 0f).normalized;
        transform.Translate(direction * speed * Time.deltaTime);
    }
}

(the speed is set to 80 if that matters)

The player has a circle collider 2d and a rigidbody 2d and the wall has a polygon collider 2d and a rigidbody2d (I had heard that technically a rigidbody wouldn’t be necessary if the player has one already, but for some reason it wouldn’t work if the wall didn’t have any). They don’t have any materials attached to them.

So what’s the problem? Well, my player does seem to know that the walls are walls, and it slows down as it comes in collision with the wall, but it can still walk through the wall if you keep pressing. I would like for the wall to be completely impenetrable, but I can’t seem to make that work :frowning:

Things I’ve tried:
-Making sure that none of the box collider have IsTrigger checked (they don’t).
-Using OnCollisionEnter2D to bring the speed to 0 once they come into collision (the speed does go to 0, but then it stays that way so the player can’t move anymore, which is not what I want).

What can I do to make the walls completely impenetrable? Thank you so much in advance and I’m sorry if this is long, I just wanted to make sure this was detailed (I can add screenshots of the components if necessary, there’s just an image limit here haha).

Since your character has a rigidbody attached you will need to move the character through it’s rigidbody and not it’s transform. You will need to get a reference to the rigidbody attached to the character, then in your update you would used the rigidbody’s MovePosition() method. In the end you should have something that looks like this:

this.rg2d.MovePosition(this.rg2d.position + (direction * speed * Time.deltaTime));

Rigidbody’s MovePosition Documentation