Raycasting from center of screen instead of mouse location

I’m trying to change my code to fire a raycast from the center of the screen instead of the mouse position. I’m very new to raycasts so I am unsure what is wrong with my code.

Current code that works.

if(Input.GetMouseButtonDown(0) &&
       collider.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit,
                        Mathf.Infinity)) {

}

Code that I want to change it to.

if(Input.GetMouseButtonDown(0) &&
       collider.Raycast(Camera.main.ScreenPointToRay(Screen.width / 2, Screen.height / 2, 0), hit, Mathf.Infinity)) {

}

It doesn’t work when I try calculating in the screen position.

I’m not entirely sure why your 2nd code doesn’t work, but this Ray should:

Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f))

You will need to encapsulate your integers in a Vector3, like this:

if(Input.GetMouseButtonDown(0) &&
       collider.Raycast(Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, (Screen.height / 2, 0)), hit, Mathf.Infinity)) {

}

Note that I have inserted new Vector3() around your three integers, that will cause them all to be a part of a newly created Vector3 object, which ScreenPointToRay can use : D

EDIT:

As Kat0r has pointed out,

Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));//C# version
Camera.main.ViewportPointToRay(new Vector3(0.5, 0.5, 0.0));//JS version

Is another (slightly faster) way to get the center of the screen

if this is C# then cast the params to float:

(float)Screen…

If US I’m not sure you can do that, but you can assign them to floats:
var x: float = Screen…

Then use x

I do this all the time.

You cannot just declare, “Hey, x is now y!”. You have to say, “Hey, x is a NEW VECTOR3 that is == to y!”.

So to make your code work, which I literally just found and copy pasted for my needs and worked perfectly afterwards, is this;

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