How to lock an object's transform.forward?

I’m trying to lock an object a certain distance from a wall, so the player can move up/down and side to side, but can’t move away from the wall.

Right now, my code looks like this:

RaycastHit hit;
LayerMask mask = LayerMask.NameToLayer("Wall");
if (Physics.Raycast(this.transform.position, transform.forward, out hit)) {
	Vector3 normal = hit.normal;
	distance = hit.point + (-transform.forward * wallDistance);
	this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, distance.z);

And in Update, the player will be kept distance wallDistance away from the wall.

Problem is, this will only work if the player is hitting a wall along the z axis. If the player were to instead be running along the x axis, and they hit a wall, they’d be unable to move side-to-side along the wall (z-axis), while able to move away from the wall (x-axis).

My question is, how do I lock the player in a certain value of transform.forward, while simultaneously allowing movement in transform.right and transform.up?

You are close. Your ‘distance’ calculation is actually a position calculation. For line 6 try this (and delete line 5):

transform.position = hit.point - transform.forward * hit.distance;

Note this will work when the object is facing directly at the wall (any wall), but if player will be at angles to the wall, you’ll have to take a different approach.