- Home /
Raycast based on crosshair on screen
Hello
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.
Thanks.
Answer by amirabiri · May 22, 2012 at 08:26 AM
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.
Thanks. I got it working but I had to detach the camera from my character.
I have the camera attached to the character's bone so it moves along with the animations and this makes the rays go in totally the wrong direction.
Any ideas?
The ray will always genuinely represent the screen point in the world in the current frame. The question is what are you trying to achieve?
If you want the camera to move around with the movement of the character then the different ray casts represent the result of this effect.
If you just want to achieve a simple "head bob" effect without the complexity of putting the camera on a bone then consider making a simple script that jigs the camera around a certain point depending on the movement speed of the character.