Hi everyone, how do you get a SphereCast in the exact center of the screen? I tried the following below but I’m not sure if it’s correct.
if(Physics.SphereCast(new Vector3(Screen.width / 2, Screen.height / 2, 0), 2f, gameObject.transform.forward, out hit, 100))
- Unity has four coordinate systems, Viewport, Screen, World and GUI. You are passing a Screen coordinate to a function that takes a World coordinate.
- SphereCast() takes a sphere of a radius you specify and moves it in the direction you specify for the length you specify. It returns the first object that would have produced a collision with the sphere. If you are trying to detect object at the center of the screen, then you want to use Physics.OverlapSphere() or Physics.CheckSphere().
- The screen is a 2D space and the world (where SphereCast() works) is a 3D space. So any time you make a conversion between 2D and 3D you have to ask at what distance from the camera.
To make the conversion:
v3Pos = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10.0f));
Viewport points start at (0,0) in the lower left and go to (1,1) in the upper right, so (0.5,0.5) will be the center of the screen. The ‘Z’ parameter will be the distance in front of the camera.
what you want to do is use the Camera.main.ScreenPointToRay function with the coordinate you are using the resulting ray