How do I calculate how far along a point is in relation to a line, when the point is not on the line?

I have a 2D plane with a texture on it. By clicking on the texture I can select a colour by making use of Raycasting and RaycastHit.textureCoord.

As part of a virtual reality pointer (in combination with the Razer Hydra) I want to use a collider instead. It’s a small sphere that intersects with surfaces, and by clicking I can select objects. Because I can’t Raycast in this case, how would I go about getting an x and y coordinate, where the sphere intersects the plane? The goal is to get values between 0 and 1: bottom left is 0,0, and top right is 1,1. This also has to work when the plane is scaled, rotated, and moved.

One way I tried to approach it is this:

In this example image the red rectangle is the selection plane, the yellow sphere is the selection collider, and the four purple spheres are the Transform handles as children of the rectangle game object. (Ignore the two-tone blue background.)

alt text

  1. Add four Transforms as children of the plane, placing them on the top, right, bottom, and left edges. Shown in the image as the purple spheres.
  2. To calculate the x coordinate I took the distance from the left sphere to the collider (left-collider) and added the distance from the rightsphere to the collider (right-collider). Then I took the distance left-collider and divided it by the sum of the two distances.
  3. I repeated this for the y coordinate by taking the top and bottom colliders.

In the following example point p is 1.5 units away from point l, and 4.5 units away from point r. Adding these distances we get 6: 1.5 + 4.5. Dividing 1.5 by 6 gives us 0.25, which is correct.

alt text

The problem is that this works fine when point p is relatively in line with the line left-right, but when point p is higher or lower, and thus farther away from both left and right, the proportion is no longer correct.

My question is as follows:

  1. How can I calculate how far along a point is along an axis when the point is not actually on the axis?
  2. Is there a better/easier way to calculate this point than using two or more handles as anchors?

Thank you very much for your time. I hope I explained my question well enough, but in case I haven’t, I’d be happy to elaborate.

The common math solution is to use local space. Assume that left-most blue ball has its Z-axis facing right, directly along the plane. So it can “count as” the plane’s personal (000,) while it’s axis are the plane’s personal xyz.

If we can put something in that ball’s localSpace coords, then z will be distance along the plane, and x will be L/R from the center of the plane.

Use: Vector3 pLocal = leftBall.InverseTransformPoint(selectedPoint);

(and look up InverseTransform examples, since there are always some tricky bits.)