How to determine the closest point on a line to another point

I’m making a game where you can change paths whenever the player wants but I don’t know how to make the player change paths like on the image below.
43367-point-on-a-path.jpg

The player also needs to maintain the direction that he is going to.

Thank you for your help.

I’m using the following code to draw my path:

public class RailPath : MonoBehaviour 
{
	public PathPoint [] nodes;

	[System.Serializable]
	public class PathPoint
	{
		public bool jumpToThisPoint;
		public Vector3 point;
	}

	public int [] path;

	void OnDrawGizmos()
	{
		for (int i = 0; i < nodes.Length; ++i)
		{
			Gizmos.DrawWireSphere(nodes*.point, 0.5f);*
  •  	if (i > 0)*
    
  •  	{*
    

_ Gizmos.DrawLine(nodes*.point, nodes[i -1].point);_
_
}_
_
}_
_
}_
_
}*_