This content originally appeared on Level Up Coding - Medium and was authored by Mohamed Hijazi
If you have read my previous progression article (Zombie Progression Report: Player Movement & Shooting Unity 3D), then you would know that we applied Ray Casting in order to shoot.
In this article, I will go a little deeper and explain how this is done and what does it mean to Ray Cast.

Definition
Ray casting is part of Unity’s Physics system It is a method that allows you to shoot a ray (like a laser) from an origin point in a certain direction of a max distance length. The exact point of contact between the ray and the other object it collided with returns a hit info which is super helpful.
The default syntax for RayCasting is:
Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);
LayerMask is optional which allows you to filter which objects that this ray can collide with.
Practical Example
In our zombie shooter project (link at the top of this article) we want to allow our player to shoot a weapon. We decided to use Raycasting in order to shoot from the center of the camera (gun reticle).
- Using the new Input system, we change a boolean “_canShoot” when the player click the left mouse button.
- Define a ray coming from the center of the camera. Unity has a very hand method called “ViewportPointToRay(new Vector3(x,y,z)” which returns a ray shot from the view port of the camera. Viewport coordinates are normalized and relative to the camera. The bottom-left of the camera is (0,0); the top-right is (1,1). So the center is x=0.5f and y = 0.5f.
- Use the Physics.Raycast to detect the hit information of the ray we shot above. If the ray hits the target, then we will call the target’s Damage method to deal damage to them.
- Encapsulate all of this with a cooldown system .

Here is how it looks in-game with some blood.

If you want to know how I added blood splatter to the point of impact between the ray and the enemy, let me know in the comments.
Tip of the Day: Ray Casting in Unity was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Mohamed Hijazi

Mohamed Hijazi | Sciencx (2021-06-29T16:01:01+00:00) Tip of the Day: Ray Casting in Unity. Retrieved from https://www.scien.cx/2021/06/29/tip-of-the-day-ray-casting-in-unity/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.