Is it possible to block player movement?

Is it possible to block player movement? Not all movement, just specific movements/inputs. Say if I want the player to be able to walk forward and backwards but prevent them from moving right or left.

I tried blocking the movement with barriers and invisible walls but they are still able to turn. I need to block left and right movement all together. Is this possible?