How to implement shooting game logic in Unity (Part 1)

Unity offers an exciting platform for game developers, and implementing a shooting system with 3D bullets is a key skill. This guide outlines the process, adaptable to various game mechanics and requirements.

This Answer is part of the introductory series on how to build a first-person shooter game using Unity.

Let’s dive into what we’ll be creating together in this tutorial.

Note: This Answer has been created using Unity version 2021.3.6f1 (LTS).

Step 1: Scene setup in Unity

First, create a new Unity 3D project or open an existing one. The default project includes a “Main Camera” and a “Directional Light” in the “Hierarchy” window.

Step 2: Weapon creation basics

A weapon is an asset that fires a projectile. We can create a weapon by importing an asset from the Asset Store or using 3D primitive shapes. For simplicity, let’s use a Cylinder 3D primitive GameObject.

  1. First, create an empty GameObject and rename it “Player.”

  2. Navigate to Edit > GameObject > 3D Object > Cylinder to create a Cylinder 3D primitive. Make it a child of the Player GameObject, then rename it to “Weapon.”

  3. Extrapolate it to resemble a thin cylinder, imitating a weapon’s nozzle.

  4. Rotate it in the opposite direction of the camera to make it appear as if the player is holding the weapon.

  5. Finally, add a material to distinguish it from the background.

canvasAnimation-image
1 of 3

Step 3: Configuring the bullet spawn point

We know that for each weapon, the spawning point of a bullet is right in front of it, as shown in the illustration below.

Spawning point
Spawning point

To establish the origin point for bullet spawning, we need to add a new child GameObject to the Weapon GameObject. Name this child GameObject “BulletSpawnPoint and strategically position it right in front of the weapon. This setup is crucial as it determines the exact location from where the bullets will be fired in the game.

Positioning BulletSpawnPoint GameObject
Positioning BulletSpawnPoint GameObject

Step 4: Create the bullet

Now is the moment to create a bullet. Opt for a Sphere primitive 3D GameObject to mimic the bullet and attach a Rigidbody component to it for physics interactions. Enhance the bullet’s visibility by attaching a material with a red color to the GameObject. For streamlined creation and handling of bullets during gameplay, transform the Bullet GameObject into a Prefab.

Positioning Bullet GameObject
Positioning Bullet GameObject

Step 5: Firing script development

Create a C# script named WeaponHandler to manage the bullet-firing functionality in the Unity shooting game. This script should be attached to the Weapon GameObject, enabling it to shoot bullets effectively. Understanding C# scripting in Unity is crucial for developing interactive game elements.

using UnityEngine;
public class WeaponHandler : MonoBehaviour
{
[SerializeField] private Transform bulletSpawnPoint;
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private float bulletSpeed = 10f;
private void Update()
{
HandleInput();
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
FireBullet();
}
}
private void FireBullet()
{
GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();
if (bulletRigidbody != null)
{
bulletRigidbody.velocity = bulletSpawnPoint.forward * bulletSpeed;
}
}
}

This script enables shooting functionality by instantiating bullets at a designated spawn point and propelling them forward with a constant speed when the “Space” key is pressed.

  • Lines 14–20: The HandleInput method checks if the “Space” key (KeyCode.Space) has been pressed. If it has, then it calls the FireBullet method to fire a bullet.

  • Lines 22–30: The FireBullet method handles the firing of the bullet. It uses Instantiate to create a new instance of the BulletPrefab GameObject at the bulletSpawnPoint position and rotation. It then retrieves the Rigidbody component from the Bullet GameObject. If the bullet has a Rigidbody, it sets its velocity to bulletSpawnPoint.forward * bulletSpeed. This line of code makes the bullet move in the forward direction of the bulletSpawnPoint with a speed defined by bulletSpeed which is defined in line 7.

Now drag and drop Bullet prefab as well as BulletSpawnPoint into the empty fields of the component.

Step 6: Adding bullet physics

To ensure that bullets interact with the environment and other objects, add a Rigidbody component to the bullet prefab if it is not already present and set “Is Kinematic” to false. Additionally, add a “Collider” to the bullet to detect collisions with enemies or other elements in the scene.

Create the following BulletHandler script and attach it to the bullet prefab.

using UnityEngine;
public class BulletHandler : MonoBehaviour
{
public float lifeDuration = 1f;
private void Start()
{
DestroyBulletAfterLifetime();
}
private void DestroyBulletAfterLifetime()
{
Destroy(gameObject, lifeDuration);
}
}

So, when the BulletHandler script is attached to a GameObject, it will destroy that GameObject (bullet) after the specified lifeDuration duration in seconds. For example, if we have a bullet GameObject with this BulletHandler script attached and lifeDuration is set to 1, the bullet will exist for one second before being automatically removed from the scene.

Here is the output of the above script attachment.

Step 7: First-person viewpoint integration

We’ve made significant progress toward creating a basic first-person shooter game. Next, we’ll set up the camera to simulate a first-person perspective, allowing it to be moved using the arrow keys. To achieve this, attach the PersonController script, as outlined in the “implement first-person viewpoint” Answer, to the Camera. Additionally, link the PlayerMove script from the “controlling a GameObject using arrow keys” section to the Player GameObject.

Now, it’s time to play the game.

Play here!

Note: Click the “Run” button below to start the game. Once the game is rendered, interact with it by clicking on the “Output” screen. Alternatively, you can access the game by clicking the link provided below:

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Here is the simple shooting game logic in Unity. In the next Answer, we’ll be implementing a weapon-switching system in Unity.


Next: How to implement a weapon-switching system in Unity

Copyright ©2024 Educative, Inc. All rights reserved