Journal 115 — Unity 3D Zombie Shooter, Target and Raycast
Objective: to update the mouse controls and create a target where the mouse points and Raycast shooting to check for a hit
To build on the previous article, we will add a target system with the mouse movement, and we will use Raycast to check for hits.
To start, we can add a 2D sprite of a target / reticule of your choice on a UI image component, and zero out the position to fix it in the middle of the screen.
We can modify the mouse look script slightly to avoid what looks like shooting the player, and also to look higher on the screen. By looking in the Inspector, we can use a range of about 0 degrees to 28 degrees.
Let’s try modifying further to look higher. This pushes the max and min range to negative values. Ideally I would like to get a view looking straight up, about -90 degrees.
Not working…
With a bit of searching, I found a slightly modified method using Quaternion.Euler instead of Quaternion.AngleAxis. In addition, as negative degrees are not possible, the modified method includes a couple bool conditions to restrict the clamp. So for example, I want to view from 0 degrees down to 28 degrees, which puts the reticule just above the player’s head. The next bool condition converts the rest of the clamped range (0 to -90 degrees) from 270 to 360 degrees.
Now to see if this works…
Success!
Raycast
Let’s start the Raycast setup with 3 cubes on screen to aim at.
Let’s make a “Shoot” script and attach it to the Player.
Now we can see what happens.
Thank you for your time!