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))
2 Answers
2
- 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
I switch to Camera.main.ScreenPointToRay but I'm getting an error from the console saying that I have some invalid arguments. if(Physics.SphereCast(Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)), 2f, gameObject.transform.forward, out hit, 100f))
– OchreousWhat you should do is send a ray from the center of the screen. Then when the ray hits something, you use the hit.point to get the exact point of impact. You then create the overlap sphere at the hit.point.
– Lairinus@Shingox what exactly are you trying to do? I don't quite understand. My spherecast is hitting objects. It's just not in the center of screen.I'm trying to figure out how to get my Spherecast in the center of the screen. I have no idea if my SphereCast is in the center or not.
– OchreousNow it seems to be hitting anything in the center of my gameobject rather than the center of my screen. if(Physics.SphereCast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)), 2f, out hit, 100f))
– Ochreous@Shingox - you are passing a viewport coordinate to ScreenPointToRay. You want ViewportPointToRay() if you are going to use (0.5, 0.5, 0).
– robertbu