- Home /
Ray through camera
Hi all,
I have what I thought was some very simple code. I want to cast a ray through the camera to the global 0,0,0 position.
void Update () {
Ray ray = camera.ViewportPointToRay(new Vector3(0,0,0));
Debug.DrawRay(ray.origin, ray.direction * camera.farClipPlane, Color.yellow);
}
This just seems to cast a ray along the bottom left frustrum line and has no bearing on camera position in relation to the zero position.
Any help would be great!
Answer by robertbu · Jul 03, 2014 at 06:45 AM
Viewport coordinates start at (0,0) in the bottom left corner, and go to (1,1) in the upper right. So your code is casting a ray into the scene from the bottom left of the camera viewport. It seems you want to cast from the center of the camera to the world origin. You can use a version of the Raycast that takes a position and a direction:
Vector3 origin = camera.transform.position;
Vector3 direction = -transform.position;
if (Physics.Raycast(origin, direction)) {
// Do something
}
And the Debug.DrawRay() would be:
Debug.DrawRay(origin, direction);
Ah thanks, that makes a lot of sense, I was misunderstanding the use of ViewportPointToRay.
Your answer
![](https://koobas.hobune.stream/wayback/20220613153044im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I keep functionality of LookAt script whilst using it in a 3dGUI camera layer? 0 Answers
Detect Mouse in right side or left side For Player? 2 Answers
i don't understand Vector3.forward correctly on camera 1 Answer
Distance Variable Won't Change. What's Wrong With My Script? 1 Answer
Start raycast from object 1 Answer