Calculate x,y,z coordinates where ray intersects sphere

I know this is more of a math question but I also need to know which functions to apply in Unity.

I have a 3D radar system in my game that displays ships in space as blips on a small readout. It works fine except that there is no upper limit to the distance a blip can be from the center of the readout. As a result, it is possible to completely lose track of ships that are very far away.

I want to create an upper limit to my radar display so that when a blip goes beyond a certain distance, it “sticks” to the very edge of the display. That way I will at least know which direction to turn to pursue the ship.

I think the way to handle this is to calculate the x,y,z coordinates where a ray (drawn from the center of the radar display to the true location of the blip) intersects the upper boundary of the display, which would be a sphere of 2 units radius.

Right now the location of a blip is calculated like this:

_rblips <em>.position = (_RadarBlips *.Target.transform.position - CenterPoint.transform.position) / RadarScale;*</em>

Where Target.transform.position and CenterPoint.transform.position are positions in “real” space (Centerpoint is the player’s ship) and RadarScale = 1000.[19891-xyz_2.jpg|19891]*
If the blip goes beyond the 2 unit boundary of my display, I’d like to move it to the very edge of my display like the above pic.
*
I tried some basic trig functions but I’m not sure if I’m calculating the original angle correctly. Has anyone tried something like this?

  • Take a Vector3 that represents target’s position relative to the centre of the sphere
  • If the magnitude of this Vector3 is less than or equal to the radius of your sphere you can use this directly, as it is within the sphere.
  • If the magnitude exceeds the radius of the sphere then normalise the Vector3 and multiply with the radius. This will result in a point on the surface of the sphere.

Figuring out the intersection of a sphere is easy, but, unless this is a 2D game, I don’t think that is a solution to your problem. So to give you what you ask for and move the blip to no more than 2 units from your center, do the following after you do the calculation above:

if (_rblips *.position.magnitude > 2.0) {*

rblips .position = rblips .position.normalized * 2.0;
}

But if this is 3D, then I think you need to do some sort of projection to 2D before you do the limit. How you do that projection will depend on your setup.