Raycasting In Unity

Ali Emre Onur
2 min readJun 1, 2021

If you are somehow familiar with game development, you probably already know that Raycasting is used for detecting if we shoot a target by sending an invisible ray. If the ray hits on a game object of interest, we can easily gain access to the game object within script.

Here’s the link for Unity Manual for Raycast in 3D. https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

If you have been following my articles, you might remember that I have also used Raycasting in the 2.5D Platformer game, to detect if the player is grounded or not. Certainly, Raycasting can be used for many other purposes.

Back to the shooter game. Shortly, the idea is to create the ray starting from the middle of the screen, right from the center of the crosshair. Despite using the transform.position of the player might seem to work, the ray would be originated from the player’s position rather than the center of the screen. Thus, we need to make sure that the origin of the ray is the center of the camera.

I have learned that Viewport is the game view. So, I actually want to cast a ray from the center of the viewport. If you check the Unity Manual for Camera.ViewportPointToRay from here, you will observe that it is actually easy to gather the center of the camera.

Thus, the coordinate (0.5f, 0.5f) will precisely give out the center of the camera.

Shoot Script

And the result: