How to make a gameobject only move between two empty gameonjects

I have a game object with two empty objects attached: pos1, and pos2. How could I go about making so once my player does a specific function his transform.position becomes limited to the “line” between two objects.
_
I have a Character Controller, and when the player does a certain function it moves the player to the hit.point of my game-object wall. However once he’s on the wall, I’d like some code to limit him only on his horizontal axis between the two point on the wall. Almost like he’s in cover, so he shouldnt be able to do anything but go left or right.
_
Any insight?
_
I found this and was going to apply this to my code, however someone could tell me if this is counterproductive or if there is a more efficient way.

public class Example2 : MonoBehaviour {
     private Vector3 pos1 = new Vector3(-4,0,0);
     private Vector3 pos2 = new Vector3(4,0,0);
     public float speed = 1.0f;
 
     void Update() {
         transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong(Time.time*speed, 1.0f));
     }
 }

Pingpong is going to literally ping pong the values between pos1 and pos2.

I’m assuming you want the freedom to move your player when you want (and not just go back and forth) If you don’t want the value to do that you should clamp your values: Mathf.Clamp(transform.position.x, pos1, pos2); that way your player has the freedom to move along the axis freely (without going outside the bounds).

You also might want to switch your Vector3 to a Vector2 if you’re only in one axis. OR even do a single float and do: Mathf.Clamp(transform.position.x, -4, 4);