When I approach a fence from behind, the character should be able to walk "behind" it:

But at the same time, when the player approaches the fence from the front, it should look like this:

The only solution I found is using the star passability for the fence and disable being able to walk through it via the 4 direction movement (which works), but I end up in this situation:

I know why this is happening, but I can't think of a way to solve it.
Is there any way (maybe via events?) to do this?