Creating Bullet Holes via Raycasting

Tyler Smallwood
3 min readJun 12, 2023

--

Objective: Instantiate Bullet Holes on walls with Raycasting.

I will use the Raycasting system to shoot a ray from the center of the screen when I left click and take that hit point to have a bullet hole to show up. The assets I used are from FileBase.

I start off with a new script to handle the shooting. In this new script we need to use the new input system.

There is a need for the bullet hole prefab. So we create a variable to hold it.

In Update check for the left mouse button click and create a local RaycastHit variable.

To get the center of the screen we will need to create a rayOrigin assigned the Camera.Main.ViewportPointToRay(Vector3). For the vector3 we will instantiate a new Vector3 with both X and Y axis set to .5f and that will be the center of the screen. Once we have the Ray done we will check to see if the Physics.Raycast hits anything.

Now it’s time to Instantiate the bullet prefab and the location of hitInfo.point. That returns the position where the ray hit. To make sure the BulletPrefab is facing the correct way we will use Quaternion.LookRotation and pass in the hitInfo.normal.

Now we can see that we hit something. You may notice that the bullet holes look to be fighting with the walls position by fading in and out. That’s because the Box collider and Wall are exotically the same. It is causing both objects to occupy the same spot.

To fix the bullet holes occupying the same spot, you can make the Box Collider a little bit bigger on the respective axis. For this project it is the Y axis.

Now there is no more fading in and out of the bullet holes! Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet