Raycast to the centre of the screen in Unity 3D

Daniel Kirwan
2 min readOct 6, 2021

Objective: Use the centre of the screen to shoot a ray and determine the object being hit

If you’re making a third person or First person game, you will at some point want the player to interact with something, whether that be by shooting a weapon or by picking up an object. In my case I will want the player to shoot stuff.

To do this, I will need to fire a raycast from the centre of the screen which will be where the player is always looking.

This is a simple script that I have kept separate from the main player script called Shoot.

When the player clicks the left mouse button I create a Ray by using the main camera in the scene. I use it to convert from the viewport point to a ray. The new vector3 is the position in the viewport that you want the ray to be. The left side of the screen(x-axis) is 0 and the right is 1, the bottom(y-axis) is 0 and the top is 1. So, 0.5 and 0.5 would be the centre of the screen.

I then create a raycasthit variable, this is needed for every raycast that you do, this is so that you can get information from the raycast if it has hit something. I have wrapped the raycast in an if statement, so if the ray hits something, it will then run the code below. In this example it is logging the name of the object the ray has collided with.

And that is it for firing a raycast.

--

--