Reputation: 24641
I want to cast ray from middle of the screen now I do it by using mouse and set the mouse in the middle but it can causes bugs. I use:
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
What should I use instead?
Upvotes: 1
Views: 7270
Reputation: 20033
In my experience I found that a Debug Ray (a ray which shows up in the Editor's Scene view) is a great help when working with Rays.
Vector3 rayOrigin = new Vector3(0.5f, 0.5f, 0f); // center of the screen
float rayLength = 500f;
// actual Ray
Ray ray = Camera.main.ViewportPointToRay(rayOrigin);
// debug Ray
Debug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayLength))
{
// our Ray intersected a collider
}
The Debug Ray is only available in the Scene view, while the game is running. If you want to draw a line in-game, look into LineRenderer.
Upvotes: 4