Craft a very detailed step by step plan tutorial to make a counter strike FPS game in Unity. Your plan tutorial must be easily understandable even for first time coders. We don't use any external asset currently, so feel free to use generic 3d models.
Assistant
How to Create a Basic First-Person Shooter Game in Unity: A Step-by-Step Tutorial for Beginners
Welcome to this comprehensive tutorial on creating a basic First-Person Shooter (FPS) game in Unity, inspired by games like Counter-Strike. This guide is tailored for beginners—even if you've never coded before, you'll be able to follow along and create your own FPS game using generic 3D models provided by Unity.
Table of Contents
Introduction
Setting Up Unity
Creating a New Project
Setting Up the Scene
Creating the Player Character
Implementing Player Movement
Adding a First-Person Camera
Implementing Shooting Mechanics
Adding Targets (Enemies)
Implementing Health and Damage
Adding User Interface (UI) Elements
Testing and Debugging
Final Touches
Conclusion
1. Introduction
In this tutorial, we'll create a simple FPS game where the player can move around a scene, look around with the mouse, and shoot targets. We'll cover the basics of:
Setting up a Unity project.
Creating a player character with movement controls.
Implementing a first-person camera.
Adding shooting mechanics using raycasting.
Creating targets that can be destroyed.
Displaying a health system.
Adding basic UI elements.
By the end of this tutorial, you'll have a foundational FPS game that you can build upon and customize further.
Download Unity Hub: Unity Hub is a management tool that helps you install different Unity versions and manage your projects.
Install Unity Hub: Run the downloaded installer and follow the prompts.
Install a Unity Version:
Open Unity Hub.
Click on the "Installs" tab.
Click "Add" and select the latest LTS (Long Term Support) version of Unity.
Click "Next" and select the "Microsoft Visual Studio Community" component for script editing.
Click "Done" to start the installation.
3. Creating a New Project
Step 1: Launch Unity Hub
Open Unity Hub.
Step 2: Create a New Project
Click on the "Projects" tab.
Click the "New Project" button.
Choose the "3D Core" template.
Give your project a name, e.g., "MyFirstFPSGame".
Choose a location on your computer for the project.
Click "Create".
4. Setting Up the Scene
Step 1: Understanding the Unity Editor
When your project opens, you'll see the Unity Editor, which consists of several windows:
Scene View: Visual representation of your game world.
Game View: What the player will see when the game is running.
Hierarchy: Lists all the GameObjects in your scene.
Inspector: Shows properties of the selected GameObject.
Project: Contains all your assets (models, scripts, etc.).
Step 2: Creating the Environment
Add a Ground Plane
Right-click in the Hierarchy window.
Select 3D Object > Plane.
Rename the plane to "Ground":
Select the plane in the Hierarchy.
In the Inspector, at the top, change the name.
Scale the Ground
With the Ground selected, go to the Inspector.
Find the Transform component.
Set the Scale to (10, 1, 10) to make the ground larger.
Step 3: Adding Some Obstacles
Create Cubes as Obstacles
Right-click in the Hierarchy.
Select 3D Object > Cube.
Position the cube somewhere on the ground by changing the Position values in the Transform component.
Duplicate and Position Obstacles
Select the cube in the Hierarchy.
Press Ctrl+D (or Cmd+D on Mac) to duplicate.
Move the new cube to a different position.
Repeat to create multiple obstacles.
5. Creating the Player Character
Step 1: Add a Player Capsule
Right-click in the Hierarchy.
Select 3D Object > Capsule.
Rename it to "Player".
Step 2: Position the Player
With the Player selected, set the Position to (0, 1, 0) in the Transform component.
Step 3: Add a Character Controller
With the Player selected, click "Add Component" at the bottom of the Inspector.
Type "Character Controller" and select it.
This allows the player to interact with the environment physically.
6. Implementing Player Movement
We'll create a script to handle player movement.
Step 1: Create a Scripts Folder
In the Project window, right-click and select Create > Folder.
Name it "Scripts".
Step 2: Create the Player Movement Script
Open the Scripts folder.
Right-click inside the folder and select Create > C# Script.
Name it "PlayerMovement".
Step 3: Write the Movement Script
Double-click the PlayerMovement script to open it in Visual Studio.
Replace the contents with the following code:
csharp
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6.0f; // Movement speed
public float gravity = -9.81f; // Gravity force
public float jumpHeight = 1.0f; // Jump height
private CharacterController controller;
private Vector3 velocity; // Player's current velocity
private bool isGrounded;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
// Check if player is on the ground
isGrounded = controller.isGrounded;
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f; // Small negative value to keep the player grounded
}
// Get input from keyboard
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
// Move in the direction based on input
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
// Jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// Apply gravity
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Step 4: Attach the Script to the Player
Save the script in Visual Studio (Ctrl+S or Cmd+S).
Go back to Unity.
With the Player object selected, drag the PlayerMovement script from the Project window to the Inspector to add it as a component.
7. Adding a First-Person Camera
Step 1: Create a Camera
Right-click in the Hierarchy.
Select Camera.
Rename it to "PlayerCamera".
Step 2: Make the Camera a Child of the Player
Drag the PlayerCamera onto the Player object in the Hierarchy.
This makes the camera move with the player.
Step 3: Position the Camera
Select PlayerCamera.
In the Transform, set the Position to (0, 0.5, 0).
This positions the camera at the player's eye level.
8. Implementing Shooting Mechanics
We'll allow the player to shoot by clicking the mouse button.
Step 1: Create a Shooting Script
In the Scripts folder, create a new C# script named "PlayerShooting".
Open the script and replace its contents with:
csharp
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public float range = 100f; // How far the gun can shoot
public Camera fpsCam;
void Start()
{
// If the camera isn't set, find it
if (fpsCam == null)
{
fpsCam = GetComponentInChildren<Camera>();
}
}
void Update()
{
// Check for mouse button down
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
// Create a ray from the camera centered forward
Ray ray = fpsCam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, range))
{
Debug.Log("Hit " + hit.transform.name);
// Check if the object has a Target script (we'll create this later)
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(10); // Deal 10 damage
}
}
}
}
Step 2: Attach the Script to the Player
Save the script.
In Unity, select the Player object.
Drag the PlayerShooting script onto the Inspector to add it as a component.
9. Adding Targets (Enemies)
We'll create simple targets that can be destroyed when shot.
Step 1: Create a Target Script
In the Scripts folder, create a new C# script named "Target".
Open the script and replace its contents with:
csharp
using UnityEngine;
public class Target : MonoBehaviour
{
public float health = 50f;
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
void Die()
{
Destroy(gameObject); // Destroy the target
}
}
Step 2: Create Target Objects
Right-click in the Hierarchy.
Select 3D Object > Sphere.
Rename the sphere to "Target".
Position the Target somewhere in the scene using the Transform component.
Attach the Target Script:
With the Target selected, drag the Target script onto the Inspector.
Step 3: Duplicate Targets
Select the Target in the Hierarchy.
Press Ctrl+D to duplicate.
Move the new target to a different position.
Repeat to create multiple targets.
10. Implementing Health and Damage
Step 1: Create a Health System for the Player
Create a PlayerHealth Script
In the Scripts folder, create a new C# script named "PlayerHealth".
Open the script and add the following code:
csharp
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public float maxHealth = 100f;
float currentHealth;
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(float amount)
{
currentHealth -= amount;
Debug.Log("Player Health: " + currentHealth);
if (currentHealth <= 0f)
{
Die();
}
}
void Die()
{
// For now, just log and reset health
Debug.Log("Player Died!");
currentHealth = maxHealth;
}
}
Step 2: Attach PlayerHealth Script to Player
Save the script.
In Unity, select the Player object.
Drag the PlayerHealth script onto the Inspector.
Step 3: Modify Targets to Damage Player
We'll simulate the targets shooting back at the player when they are destroyed.
Update the Target Script
Open the Target script.
Modify the Die() method:
csharp
void Die()
{
// Damage the player when the target dies
GameObject player = GameObject.FindWithTag("Player");
if (player != null)
{
PlayerHealth playerHealth = player.GetComponent<PlayerHealth>();
playerHealth.TakeDamage(10);
}
Destroy(gameObject); // Destroy the target
}
Set the Player Tag
Select the Player object.
At the top of the Inspector, click on "Untagged" dropdown next to Tag.
Select "Add Tag...".
Click on the "+" icon to add a new tag.
Enter "Player" as the tag name and save.
Go back to the Player object and set its Tag to "Player".
Now, when a target is destroyed, it will deal damage to the player.
11. Adding User Interface (UI) Elements
We'll add a health bar to display the player's health.
Step 1: Create a Canvas for UI Elements
Right-click in the Hierarchy.
Select UI > Canvas.
The Canvas will automatically adjust to the screen size.
Step 2: Add a Health Bar
Right-click on the Canvas in the Hierarchy.
Select UI > Slider.
Rename the Slider to "HealthBar".
With the HealthBar selected, adjust its position:
In the Rect Transform component, set Anchor to Top Left.
Set Position X to 10 and Position Y to -10.
Step 3: Adjust the Health Bar Appearance
Expand the HealthBar in the Hierarchy to see its child objects.
Select the Fill Area and then the Fill object.
In the Image component, set the Color to Red.
Step 4: Create a UI Script to Update Health Bar
In the Scripts folder, create a new C# script named "UIManager".
Open the script and add the following code:
csharp
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
public Slider healthBar;
public PlayerHealth playerHealth;
void Start()
{
healthBar.maxValue = playerHealth.maxHealth;
healthBar.value = playerHealth.maxHealth;
}
void Update()
{
healthBar.value = playerHealth.currentHealth;
}
}
Step 5: Attach the UIManager Script
Create an empty GameObject in the Hierarchy:
Right-click in the Hierarchy and select Create Empty.
Name it "UIManager".
With UIManager selected, drag the UIManager script onto the Inspector.
In the UIManager component:
Drag the HealthBar from the Hierarchy to the Health Bar field.
Drag the Player object to the Player Health field.
Step 6: Modify PlayerHealth Script to Make currentHealth Public
Open the PlayerHealth script.
Modify the currentHealth declaration:
csharp
public float currentHealth;
12. Testing and Debugging
Step 1: Test the Game
Click the Play button at the top of the Unity Editor.
Use the WASD keys to move.
Move the mouse to look around.
Click the left mouse button to shoot.
Shoot the targets to see if they get destroyed.
Observe the health bar when targets are destroyed.
Step 2: Troubleshooting Common Issues
Player Not Moving:
Ensure the PlayerMovement script is attached to the Player.
Camera Not Rotating:
We need to implement camera rotation (Next step).
Shooting Not Working:
Ensure the PlayerShooting script is attached and that the fpsCam reference is set.
13. Final Touches
Step 1: Implement Mouse Look for Camera
Create a MouseLook Script
In the Scripts folder, create a new C# script named "MouseLook".
Open the script and add the following code:
csharp
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
void Start()
{
// Lock the cursor to the screen center
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
// Get mouse movement input
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
// Rotate the camera around the X-axis (look up and down)
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f); // Limit rotation to prevent flipping
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
// Rotate the player body around the Y-axis (turn left and right)
playerBody.Rotate(Vector3.up * mouseX);
}
}
Attach the MouseLook Script
Save the script.
Select the PlayerCamera in the Hierarchy.
Drag the MouseLook script onto the Inspector to add it as a component.
In the MouseLook component, drag the Player object to the Player Body field.
Step 2: Adjust Shooting Script for Camera Movement
Our shooting script should still work, as it uses the camera's forward direction.
Step 3: Add Some Sounds (Optional)
Adding sounds can enhance the game experience.
Add a Gunshot Sound
Import a sound file into Unity (e.g., "gunshot.wav").
Drag the sound file into the Assets folder in the Project window.
Add an AudioSource component to the Player object:
Select the Player.
Click Add Component and search for Audio Source.
Uncheck "Play On Awake".
Update the PlayerShooting Script
Modify the PlayerShooting script to play the sound when shooting:
csharp
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public float range = 100f;
public Camera fpsCam;
public AudioSource gunSound;
void Start()
{
if (fpsCam == null)
{
fpsCam = GetComponentInChildren<Camera>();
}
if (gunSound == null)
{
gunSound = GetComponent<AudioSource>();
}
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
gunSound.Play();
Ray ray = fpsCam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, range))
{
Debug.Log("Hit " + hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(10);
}
}
}
}
Save the script.
Step 4: Assign the Sound Clip
Select the Player object.
In the AudioSource component:
Drag the gunshot audio clip to the AudioClip field.
14. Conclusion
Congratulations! You've created a basic first-person shooter game in Unity. You've learned how to:
Set up a Unity project and scene.
Implement player movement and camera control.
Add shooting mechanics and target interactions.
Create health systems and UI elements.
Enhance the game with sounds.
This is just the beginning. There's a lot more you can do to improve and expand your game:
Add more enemy types with different behaviors.
Implement weapon switching and ammo management.
Create more complex environments and levels.
Add multiplayer functionality.
Keep experimenting and have fun developing your game!
Note for First-Time Coders: Don't worry if some concepts seem complex at first. Programming and game development involve a lot of learning by doing. Don't hesitate to look up terms and concepts, and remember that practice is key. Enjoy the process!