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.)
- 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.
- 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.
- 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.
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:
- How can I calculate how far along a point is along an axis when the point is not actually on the axis?
- 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.