Simple - Blocking movement

Hello everyone.
I’ve created 2 gameObjects.

One of them is the player and the other one is an obstacle, I’ve 4 buttons for movement, I want the object to move around but if he collides with the obstacle I want to prevent movement(While the movement is towards that obstacle, if movement is not towards the obstacle then allow the movement…)

Is there any quick, simple and clean solution to this?

What I’ve got so far is this script attached to the player.

public void OnTriggerEnter2D (Collider2D other) {

		Debug.LogError ("TriggerEnter");
		Debug.Log (other.gameObject.name);
		canWalk = false;

			
	}

	public void OnTriggerExit2D (Collider2D other) {

		Debug.LogError ("TriggerExit");
		Debug.Log (other.gameObject.name);
		canWalk = true;
		}

But once it collides the player can’t move so I can’t really exit the collision…

Thank you for your time

Well… when you sets canWalk = false in OnTriggerEnter is logical that you can’t walk anymore, according your movement logic.

You should try implement something like canWalkFront, canWalkBack, if you don’t want to use boxcolliders to control this.

public void OnTriggerEnter2D (Collider2D other) 
{
       canWalkFront = false;
       canWalkBack = true;
}
 
public void OnTriggerExit2D (Collider2D other) 
{
       canWalkFront = true;
}