Aiming and Shooting With Crosshair- Game Dev Series 123
Objective: create a shooting function with crosshair.
Crosshair is a standard element of 1st person and 3rd person shooter game, which is what we are going to create in this article.
Create the crosshair
The concept of crosshair is simple, an image of crosshair covered the top layer of game, which is the UI.
Create an image object of UI, and drag in the crosshair image to it.
Then set the anchor to the center of screen, and scale it to a proper size. That is our crosshair.
Now we can make it as our shooting crosshair.
Raycast to shoot
To creating the shooting function, we need to create a new script to handle this part.
Create a new script, and create an if statement to detect the mouse left click insides Update().
To shoot from the crosshair, we need to create a ray from the center of screen, and detect raycasthit on objects.
In here, we use ViewportPointToRay to create this ray.
When we using ViewportPointToRay from camera, it would create a ray from camera to through viewport to the nearest object(surface). With the range from camera to viewport, the coordinate would be 0, 0 (bottom-left) to 1, 1(top right). And that is why we use 0.5, 0.5 as the center of screen.
Now we can use raycasthit to detect any hit objects with this ray.
And return its name to make sure what we exactly hit.
All done! Play and test it ,you should see the crosshair is functional now!