Raycast from Camera in unity

Viewed 142

I try to shoot a raycast from the center of the Camera not from mouse position, how can improve my code for this?

if (Input.GetMouseButtonDown(0))
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit, rango))
    {
        if (hit.transform.tag == "Player")
        {
            Debug.Log("ishitting");
        }
    }
}
2 Answers

Use this:

Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));

Placing the center of the input parameter in ScreenPoint to Position is not an optimized code and goes through several steps of long calculations. It is better to use the pure Forward.

var main = Camera.main.transform;
Physics.Raycast(main.position, main.forward, 100f);
Related