- Home /
Create a ray from camera to a Vector3 point
I have to create a ray from the main camera through an x,y,z point in space I call guidePos. The language uses screen space but no mouse click is used here. I used -
ray = Camera.main.ScreenPointToRay (Camera.main.WorldToScreenPoint(guidePos));
This works exactly how I want it but is probably very slow due to 2 camera calculations. What is the best way to create this ray? Thank you.
Answer by Eric5h5 · Dec 08, 2010 at 06:25 AM
You can do somewhere north of a million ScreenPointToRay+WorldToScreenPoint calculations per second on a half-decent modern desktop CPU. If that's your definition of "very slow", then yes, it is. But the thing that would help you the most is to cache Camera.main in a variable so you aren't retrieving it all the time.
private var cam : Camera;
function Awake () { cam = Camera.main; }
Quite so, also quite nice to use when sifting through arrays where the same object is retrieved more than once.
That should be fast enough then. I dont $$anonymous$$d the 2 functions, they are easy to read, just thought I may have missed another function that does this. I added the caching. Thank you.
Answer by Jesse Anders · Dec 08, 2010 at 05:58 AM
What you have there is probably not in fact 'very slow'. However, if you're just asking how to create a ray given two points 'p1' and 'p2', you can do it like this (untested pseudocode):
rayOrigin = p1;
rayDirection = Normalize(p2 - p1);
The normalization step is optional, strictly speaking (although it's often convenient to have the direction vector be unit length). Also, note that the above may fail if p1 and p2 are coincident or nearly coincident.
That's right. Best cod for end on this question:
Vector3 camPos = Camera.main.transform.position;
Ray ray = new Ray(camPos, pos - camPos);
Your answer
Follow this Question
Related Questions
How to use ScreenPointToRay for orthographic cameras 1 Answer
Offseting a Ray from camera before casting 1 Answer
Follow mouse cursor (with Y = 0)? 1 Answer
Get 2D Collider with 3D Ray 2 Answers