how to calculate vector perpendicular to another and apply this to object direction?

This relates to the train problem I have. It is frustrating I know it is about vectors but I just can't get it.

So I have a simulation a cube with translation along forward direction I have a ray cast to the right (90 degrees to the direction of travel I have a rail track to the right not perpendicular to the translating box I have calculated the hit.point & hit.normal The hit.normal is being shown with the draw ray it is perpendicular to the track

To make sure the cube follows the track all I need to do is find the vector perpendicular to the hit.normal and apply this normal to the cubes transform.direction

Any help would appreciated.

In 3D, there are an infinite number of vectors which are perpendicular to a single Vector in 3d space. This is because the perpendicular vector could point in any direction around the axis of the first vector.

What is generally more useful is to calculate a vector which is perpendicular to two other vectors. Those first two vectors essentially define a plane, and then it is possible to have a vector perpendicular to this plane.

For example, if you wanted to find a vector which is perpendicular sideways (along the groud) from your train track direction, you would use as the two input vectors:

1. The track forward direction vector
2. The world "up" direction vector

In addition, there can in fact be two vectors which are perpendicular to this plane, one pointing "up" relative to the plane, and one pointing "down". (or in the case of your train track, this would either be to the left or right of your track).

To get these perpendicular vector, you need to calculate the "Cross Product" of the initial two vectors. As it happens, Unity's Vector3 Class has a built-in Cross function which saves you from having to implement this yourself.

The order in which you pass the Vectors as the arguments to Cross (i.e. which is the "left hand side" and which is the "right hand side" vector) will determine whether you end up with the "up" or "down" version of the perpendicular vector.