FPS Weapon: Raycasting, bullet holes and more
Implementing an FPS Weapon in Unity
Hey, this week I want to share with you an example project about implementing an FPS weapon with sound, particle systems, raycasting and bullet holes.
FPS WEAPON
Let’s start with the fps weapon implementation.
I’m using the Modern Weapons Pack from the Asset Store, a package from 7XF Design. (Thank you guys for providing this awesome package).
This package has multiple weapons, but of course I went with the classic AK-47. I’ve imported it into the scene and add it as a child of the FPS Controller. But, please note the GameObject hierarchy – IMAGE1. The weapon does not have any scripts assigned to it. I prefer to have the mesh separated from the rest. So it’s easier to replace the weapon mesh without worrying about the breaking its behaviour.
Now, to prevent the fps weapon from being occluded by objects in front of the player – IMAGE2 – I’ve added a specific camera to render the weapon always on top of everything else:
Mesh IMAGE3
- Add the weapon mesh to a new layer;
FirstPersonCharacter IMAGE4
- Remove that layer from the Culling Mask of the Main Camera;
Weapon Camera IMAGE5
- Add a new Camera as a child of the main one (and center it’s local position and rotation);
- Change the Clear Flags to Depth Only;
- Change the Depth to 1;
- Remove all layers from the Culling Mask, except the Weapon Layer;
FPS Weapon Effects
Then, I’ve added a few visual and audio effects to make it look like the weapon it’s actually firing. These effects are all controlled by the WeaponEffects script. IMAGE6
Particle Systems IMAGE7
Please note that you can add a secondary particle system as a child of the first one. So both weapons will fire when you tell the main particle system to play.
Point Light IMAGE7
The light is fading in/out according to the particle system duration to illuminate the weapon when the particles are enabled.
Weapon Sound IMAGE8
At first I was using just a single AudioSource to play the weapon sound. But, it was being cut when shooting multiple times in a row. So, I’m instantiating a new sound prefab each time the weapon fires – WeaponSound.cs. Now, it is possible to play multiple sounds at the same time.
I’m also using an object pool to instantiate the sound prefabs. It will instantiate new prefabs as necessary and then it will recycle the disabled sounds to improve performance.
RAYCASTING AND BULLET HOLES
The weapon shooting behaviour is controlled by the Weapon script.
When the player presses the Left Mouse Button, I’m using the Physics.Raycast to cast a ray from the screen center. This ray checks for any collision and instantiates a bullet hole prefab at the collision point. IMAGE9
The bullet hole rotation is set accordingly to the hit point normal and the instance disappears after a few seconds – BulletHole.cs.
And this is it. Hope it’s useful at least as a starting point for something more complex.
Happy coding 🙂
You must log in to post a comment.