The object stops moving permanently after hitting a wall. But I expect it can move to the other directions.

I am making a top-down 2D game. I expect the player should stop moving after hitting a wall, and he can still move toward the other directions. But after adding the code below, the player just stops moving permanently.

public class MovingControl : MonoBehaviour
{
    public Rigidbody2D rb;
    public float moveSpeed = 10;
    public bool canMove = true;

    private void Awake()
    {
        rb=GetComponent<Rigidbody2D>();  
    }
    void Update()
    {
        Vector2 moveVector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        if (canMove && moveVector != Vector2.zero)
        {
            rb.MovePosition(rb.position + moveVector * moveSpeed * Time.deltaTime);
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        canMove=false;
    }
}

The player has the MovingControl + RigidBody2D + Box collider2D Components, where the RigidBody2D is Kinematic and the Box collider2D “Is Trigger” . The wall has a static RigidBody2D and a Box collider2D (without “is Trigger”). They are on the same layer.

This code will stop the player from moving after hitting the wall. But the question is, the player cannot move again. I know the reason: the “canMove” variable was set to false, and it never has a chance to become true again.But I just didn’t know where to set the variable to true again.

This may be a very basic question. I am wondering what’s the most common method that everybody use?

You can set the canMove variable to true OnTriggerExit2D. But the problem is that your solution prevents all movement when you enter the wall and so the exit trigger is unreachable.


A good solution for 2D games is the use of Raycasting. The main idea is, you cast rays every frame from your character in the direction you wish to move and evaluate by how much you can move based on the colliders you hit.


There are many good tutorials on youtube on this subject.