Raycast based on crosshair on screen


I have a camera (that moves by itself) which has a crosshair that can move freely around the screen. For the basic idea you can think of Time Crisis or games like that.

I want to be able to raycast from the camera to the object that the crosshair is over.
Basically a raycast with the origin of the destination and the correct angle to make sure it hits what the crosshair is pointing at. Though it can be done by moving the origin and having a it go straight.

I want the raycast angle to change when the crosshair moves around the screen.

I have tried camera.ScreenPointToRay(new Vector3(xPos, yPos) with xPos and yPos being the positions of the crosshair on the screen.

I have also tried ScreenToWorldPoint and ScreenToViewpointPoint all with limited success.

If anyone has any suggestions or can help at all it would be appreciated.


Camera.ScreenPointToRay is the answer, so you should double check the rest of your code. Remember that ray casts only hit colliders, check distances, coordinates, etc. If the crosshair follows the mouse, you could use Input.mousePosition.