- Home /
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 [i].position = (_RadarBlips [i].Target.transform.position - CenterPoint.transform.position) / RadarScale;
Where Target.transform.position and CenterPoint.transform.position are positions in "real" space (Centerpoint is the player's ship) and RadarScale = 1000.
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?
Answer by KellyThomas · Dec 29, 2013 at 04:38 PM
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.
Answer by robertbu · Dec 29, 2013 at 04:50 PM
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 [i].position.magnitude > 2.0) {
_rblips [i].position = _rblips [i].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.
Your answer
Follow this Question
Related Questions
creating Humanoid Motion from XYZ coordinates 0 Answers
Ignore Animations xyz values? 1 Answer
2D project with movement along Z and X? 1 Answer
tilemap 2d rendering on Y plane 0 Answers
How can I get x, y, z spawnpoints from a csv or text file? 1 Answer