Make a realistic bullets in Unity with C#

Unity realistic bullets tutorial sniper artilley

Introduction

In this tutorial you will learn how to make realistic bullets in Unity. You will need this tutorial if you are building a game where accuracy is important, such as a sniper game or if you are firing long-range artillery. You will also learn about Unity's physics engine, so if you are not into war you will also learn something new.

  • In part 1 (this part) you will create the basic scene you will need.

  • In part 2 you will learn how to calculate the angle you need to hit a target and display the trajectory path the bullet will take to hit the target.

  • In part 3 you will learn how to improve the accuracy of the bullet. We will see that Unity's physics engine is not accurate enough if you want to hit a target with high accuracy. So you have to build your own physics engine, but it's just a few lines of code, so don't worry.

  • In part 4 you will add the various forces that might affect the bullet, such as drag force and wind.

  • In part 5 you will add a sniper rifle.

...and the result will hopefully look something like this YouTube video:


Unity bullet physics tutorial YouTube video

Init

But before we begin we need a basic scene. First create a plane and rename it "Ground" and scale it to 5. Then create a box and rename it "Target" and a sphere called "Bullet" with a scale of 0.1. Make the bullet a prefab. Then create an empty Game Object called "Bullets parent" to which we will parent the bullets to get a less messy scene.

Now we need something that can fire bullets. Create an empty Game Object and rename it to "Turret." To this turret you should add a Line Renderer so we can display the bullet's path through the air. The turret also needs a body, so add a cube as a child to the Turret with position (0, 0.25, 0) and sscale (1, 0.5, 1).

Add an empty Game Object as a child to the Turret and rename it "Barrel connector." Position it at (0, 0.5, 0) in relation to the Turret so it sits on the top of the turret. Next add a cylinder as a child to the Barrel connector, and rename it to "Barrel." Resize it to (0.3, 1, 0.3), rotate it to (90, 0, 0) and position it at (0, 0, 1).

Make sure you can rotate the barrel if you are rotating the barrel connector, that you can rotate the turret, and that it looks like a turret with a gun by adding materials. Anyway, the exact dimensions are not important, but your scene should look like this (Ignore the GameController, it is just holding the camera and the light):

Unity realistic bullets tutorial initial scene

Now let's fire the gun!