Framework: Shooting through Crosshair
--
In the first step, I will create a bool variable called isPressed inside the FPS controller.
Now check in the Update method if we press the left mouse button using the new input system, then the set is pressed equal to true.
Now I create a barrier layer and an enemy layer, I will select both enemy and barrier and add the layers to them.
Go to the FixUpdate method, then create a ray that is cast in the center of the screen, we do this using ray using Camera.main.ViewportPointToRay, I will use a layer mask to hit the enemy first.
Now I will create a GameObject and transform variable called them muzzle flash and firing position. I will make an empty game object and position it to the sniper and drag the muzzle Flash to the inspector.
Now I want to Instantiate a muzzle flash every time I press a left mouse button.
Now when we hit the enemy I want to display blood particles on the enemy's body,wedo this using physics dot raycast.
If you are using an FPS camera common error, sometime the main camera tag will not have a MainCamera tag, make sure to add this tag to avoid a null exception error.
Now I want to check if we hit a collider of the enemy, using hitInfo dot collider. Then we get the AI component using hitInfor, and last we call the damage method.
Note:Why are checking collider of hit object again because physics dot ray cast will filter enemy_model collider .
A bonus here is how I fix the damage method logic in the AI script.
Let's see the result.