Unity Basics Course: Shooting 1 – Shooting with Bullets

Hello! In this course, we will create a simple shooting game using Unity. The main focus of our implementation will be on the “shooting bullets” feature. We will gradually learn the necessary functions and aim to complete a simple game at the end.

Table of Contents

  1. Installing Unity and Basic Setup
  2. Creating a Project
  3. Setting Up a 2D Game Environment
  4. Creating a Bullet Prefab
  5. Writing the Character and Bullet Shooting Script
  6. Configuring and Testing Game Objects
  7. Conclusion

1. Installing Unity and Basic Setup

To install Unity, first download Unity Hub from the Unity website. After installing Unity Hub, install the desired version of the Unity Editor. Once the installation is complete, you can run Unity Hub to create a new project.

2. Creating a Project

In Unity Hub, click the New Project button and select the 2D template. Name the project ShootingGame and set the save location, then click the Create button to create the project.

3. Setting Up a 2D Game Environment

Once the project is created, the Unity Editor will open. Here, we will place game objects and set up the camera and background.

3.1 Setting Up the Camera

Select the main camera and adjust the viewport to an appropriate size. In a 2D game, it’s common to set the camera’s Projection to Orthographic.

3.2 Adding a Background

Add an image to be used as the background in the Assets folder. Then drag it to the scene to place it. Set the z-axis value of the image lower than that of the camera to ensure the background is visible.

4. Creating a Bullet Prefab

We will create a simple sprite representing the bullet. Add the bullet sprite to the Assets folder and place it into the scene as a 2D object. After adjusting the size and properties of the bullet, drag this object into the Prefabs folder to save it as a prefab.

4.1 Setting Bullet Properties

Select the prefab and add a Rigidbody2D component. This component gives physical properties so that the bullet can move naturally. Set the Gravity Scale to 0 so that it is not affected by gravity.

4.2 Adding a Collider

Add a CircleCollider2D to the bullet prefab to set up the collider. This collider allows the bullet to detect collisions with other objects.

5. Writing the Character and Bullet Shooting Script

Now we need to write a script to control the shooting of the bullet. Let’s create the character and add the shooting functionality.

5.1 Creating the Character

Prepare a sprite to be used as the character and add it to the scene in the editor. Also, add a Rigidbody2D component to the character.

5.2 Writing the Script

Create the script for the character. Below is a basic C# script example to shoot bullets.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public GameObject bulletPrefab; // Bullet prefab
    public float bulletSpeed = 20f; // Bullet speed

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // When the space bar is pressed
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
        Rigidbody2D rb = bullet.GetComponent();
        rb.velocity = transform.up * bulletSpeed; // Set the bullet's speed in its direction
    }
}

5.3 Connecting the Script

Add the written script to the character object and set the bulletPrefab variable to the bullet prefab in the inspector window.

6. Configuring and Testing Game Objects

All components are prepared, so let’s test if the game works well.

6.1 Running the Test

Click the play button to run the game. Check if the bullet is fired when the character presses the space bar. If needed, you can adjust the speed or direction to achieve the desired outcome.

6.2 Testing Bullet Collisions

It’s also important to add handling for when the bullet collides with other objects. For example, you could make the enemy disappear when hit by a bullet. To do this, write a script for the enemy object to check for collisions with the bullet.


using UnityEngine;

public class Enemy : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Bullet"))
        {
            Destroy(gameObject); // Destroy the enemy object
        }
    }
}

Conclusion

In this course, we implemented a simple shooting mechanism using Unity. By learning the basic functions of shooting bullets and handling collisions, we have laid the groundwork for game development and a stepping stone for more advanced programming. I hope you continue to create various games with Unity!

This concludes the Unity Basics Course – Shooting 1: A Shooting Tutorial Using Bullets. If you have any questions or comments, please leave them below. Thank you!

Introduction to Unity: Function Calls

Unity is a globally renowned game engine that helps game developers bring their ideas to life. In this tutorial, we will take an in-depth look at one of the fundamentals of Unity: ‘Function Calls’. A function is a block of code that performs a specific task and plays a crucial role in game development.

1. What is a function?

In programming languages, a function is a collection of code that performs a specific task and can return a value as needed. The main advantages of functions are code reusability, readability, and ease of maintenance. By breaking complex tasks into units called functions, developers can modify and test each part independently.

2. Defining functions in Unity.

In Unity, games are developed using C#. Functions in C# are defined in the following format:

returnType functionName(parameters)
{
    // Function code
}

Here’s a simple example. This function adds two integers and returns the result:

int AddNumbers(int a, int b)
{
    return a + b;
}

3. Calling Functions

Once a function is defined, it can be called at any time. A function call is made in the following format:

returnType result = functionName(arguments);

Now, let’s call the previously defined AddNumbers function:

int result = AddNumbers(5, 10); // result will be 15.

4. Unity’s Update() Function

In Unity, there is a special function called Update() that is called every frame. This function contains code for continuously updating the state of game objects.

void Update()
{
    // Code called every frame
    if (Input.GetKey(KeyCode.Space)) 
    {
        Debug.Log("The space bar has been pressed.");
    }
}

5. Functions with Parameters

Functions can receive external data through parameters. Multiple data can be passed to functions, making them more useful. We will also look at how to use default parameters, optional parameters, and variable-length parameters.

5.1 Default Parameters

int Multiply(int a, int b = 2) 
{
    return a * b;
}

The function above has two parameters, but b has a default value of 2. Therefore, calling Multiply(5) will result in 10.

5.2 Variable-length Parameters

Using variable-length parameters allows you to adjust the number of arguments passed to the function dynamically:

int Sum(params int[] numbers) 
{
    int total = 0;
    foreach(int number in numbers) 
    {
        total += number;
    }
    return total;
}

When calling this function, you can pass any number of integers:

int total = Sum(1, 2, 3, 4); // total is 10.

6. Functions with Return Values

Functions can return values externally. This return value can be used in the function call site. The type of the return value must be specified when defining the function, and a function defined as void does not return a value.

string GetMessage() 
{
    return "Hello, and welcome to the world of Unity!";
}

7. Exception Handling and Functions

It is also important to handle exceptions that may occur during function calls. In C#, you can handle exceptions using try-catch blocks:

void ExampleFunction()
{
    try
    {
        int result = 10 / 0; // Error occurs.
    }
    catch (DivideByZeroException ex)
    {
        Debug.Log("Cannot divide by zero: " + ex.Message);
    }
}

8. Recursive Function Calls

A recursive function is a function that calls itself. This is a powerful way to solve specific problems by breaking them down into simpler subproblems. For example, we can write a recursive function to calculate the Fibonacci sequence:

int Fibonacci(int n) 
{
    if (n <= 1) return n;
    return Fibonacci(n - 1) + Fibonacci(n - 2);
}

9. Example of Game Development Using Functions

Now, let's apply functions to actual game development in Unity. We will look at a simple example of implementing a character's jumping ability:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Jump();
    }
}

void Jump()
{
    GetComponent().AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}

10. Conclusion

In this tutorial, we explored various ways to define and call functions in Unity. Functions are fundamental building blocks of all programming languages and are essential for performing various tasks in game development. Through practice and hands-on experience, enhance your understanding of function calls and create your own games!

Unity Basic Course: Pathfinding Artificial Intelligence

In game development, pathfinding AI plays a role in allowing each game object that can move to understand the environment and efficiently find a path towards a given goal. In this course, you will learn the fundamental principles and implementation methods of pathfinding AI using the Unity engine. Through this course, we will explore how to build practical pathfinding AI using basic AI concepts and Unity’s NavMesh system.

1. What is Pathfinding AI?

Pathfinding AI is a form of artificial intelligence that autonomously allows an object to move to its destination by calculating the optimal path (either many-to-many or single) based on the starting position and goal position in a given environment (map). It is commonly used in games and robotics, playing a crucial role in solving complex pathfinding problems.

1.1. The Necessity of Pathfinding

In a game environment, pathfinding AI is essential when NPCs (Non-Player Characters) or player’s assisting characters need to navigate around obstacles to reach a designated goal. For example, pathfinding algorithms are used when enemies track the player or allies move to specific points.

2. Introduction to Unity’s NavMesh System

NavMesh, a powerful tool for implementing pathfinding AI in Unity, helps calculate various paths and allows characters to move appropriately. NavMesh is a pre-calculated network of paths that enables game objects to move freely.

2.1. Features of NavMesh

  • Pathfinding based on a navigation mesh
  • Handling obstacles in the surrounding environment
  • Real-time dynamic obstacle handling
  • Accessible via a simple API

2.2. Setting Up NavMesh in Unity

  1. After creating a project, build the necessary environment.
  2. Add the ‘NavMesh Obstacle’ component to the objects where NavMesh will be applied.
  3. Open the ‘Navigation’ panel in the Unity editor, and select the Bake menu to redraw.
  4. Add the ‘NavMesh Agent’ component to the character that will be used as an ‘Agent’.

3. Implementing Pathfinding AI

Now, we will write the following script in Unity to implement pathfinding AI that can be used in actual games.

3.1. Setting Up NavMesh Agent

NavMesh Agent is AI that allows a character to move toward the target point along the NavMesh. Here is a basic example of a NavMesh Agent script:

using UnityEngine;
using UnityEngine.AI;

public class AIFollow : MonoBehaviour
{
    public Transform target; // Target point
    private NavMeshAgent agent;

    void Start()
    {
        agent = GetComponent(); // Get the NavMeshAgent component
    }

    void Update()
    {
        if(target != null)
        {
            agent.SetDestination(target.position); // Move to the target point
        }
    }
}

3.2. Setting the Target Point

The target point can be set by the user clicking in the game or specifying a particular object. The method for setting the target point via user input is as follows:

void Update()
{
    if (Input.GetMouseButtonDown(0)) // On left mouse button click
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            target.position = hit.point; // Set the target point to the clicked position
        }
    }
}

4. Applying Obstacle and Evasion Techniques

To make the pathfinding AI more realistic and natural, obstacle evasion techniques are necessary. Unity’s NavMesh can recognize dynamically generated obstacles and help the character avoid them effectively.

4.1. NavMesh Obstacle

Dynamic obstacles are objects that can change position while moving. To accommodate this, the NavMesh Obstacle component should be applied, and the ‘Carve’ option can be activated to allow NavMesh to recognize and navigate around the obstacle.

4.2. Evasion Algorithm

By adding a simple evasion algorithm, the character should be able to recognize and avoid surrounding obstacles while moving toward the user-defined target point. Additional logic can be written as follows:

void AvoidObstacles()
{
    RaycastHit hit;
    if (Physics.Raycast(transform.position, agent.velocity.normalized, out hit, 1f))
    {
        if (hit.collider != null && hit.collider.CompareTag("Obstacle"))
        {
            // Add evasion behavior when an obstacle is detected
            Vector3 avoidDirection = Vector3.Reflect(agent.velocity, hit.normal);
            agent.velocity = avoidDirection * agent.speed; // Adjust speed in the direction to avoid
        }
    }
}

5. Practical Example

Now, let’s create a simple practical example to complete the pathfinding AI based on what we’ve learned so far.

5.1. Requirements

Create a project with the following features:

  • Characters respond to user input and move to the target point
  • Artificial intelligence that avoids obstacles
  • Basic understanding of the game environment and three-dimensional space

5.2. Project Setup

Run Unity, create a new project, and set up a basic environment that includes trigger objects and colliders. Here, we will specifically set up the NavMesh to be used.

6. Conclusion

This course taught you the basic methods for implementing pathfinding AI in Unity. With the NavMesh system, you were able to implement obstacle avoidance and efficient pathfinding. Furthermore, you have gained a foundation to use this technology to implement AI for various game objects. Now, advance the AI design further to suit different types of games and apply complex algorithms.

7. Additional Materials and References

If you would like to delve deeper into the topics covered in this course, please refer to the materials below:

Unity Basic Course: Managing Enemy Character Health

Unity is one of the most widely used engines in game development. It provides the flexibility and powerful features to create games on various platforms, but there are many elements to understand and handle. In this article, I will explain in detail how to implement and manage the health of enemy characters using Unity. This process assumes a basic knowledge of C# programming. Through this tutorial, strengthen the foundation of game development and enhance the fun and challenge of your game.

1. Understanding the Concept of Enemy Characters and Health

In games, the health points (HP) of enemy characters are a very important element. Health determines how much damage the player needs to inflict to defeat the enemy character. When the health reaches zero, the enemy character dies, which can trigger various reactions in the game. By managing health, you can adjust the difficulty of the game and enhance the user experience.

2. Project Setup

First, create a new Unity project and set up a 2D or 3D game environment. The setup process is as follows:

  1. Run Unity.
  2. Click the ‘New Project’ button.
  3. Specify the project name and path, and select a template (2D or 3D).
  4. Click the ‘Create’ button to create the project.

3. Creating an Enemy Character Script

Now let’s write a script to manage the health of the enemy character. Create a new C# script and name it `Enemy`. This script will include the enemy character’s health, damage values, and health reduction methods. The following code shows a basic enemy character health management script.


using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float maxHealth = 100f; // Maximum health
    private float currentHealth; // Current health

    void Start()
    {
        currentHealth = maxHealth; // Set initial health
    }

    // Method called when taking damage
    public void TakeDamage(float damage)
    {
        currentHealth -= damage; // Reduce health
        Debug.Log($"Enemy took {damage} damage. Current health: {currentHealth}");

        if (currentHealth <= 0)
        {
            Die(); // Handle death
        }
    }

    private void Die()
    {
        Debug.Log("Enemy died."); // Death message
        Destroy(gameObject); // Delete game object
    }
}

4. Implementing the Enemy Character Health System

Before implementing the health system, let's create an enemy character object that can interact with Unity's physics engine. Create or use a new 3D model for the enemy character and adjust its position. Follow the steps below.

  1. Right-click in the Hierarchy window and select ‘3D Object’ > ‘Cube’ to add the enemy character.
  2. Change the name of the Cube to ‘Enemy’.
  3. Drag the previously created `Enemy` script onto the Enemy game object to add it.

5. Handling Enemy Damage

Now we need to implement a system that can inflict damage on the enemy. We will add a method that is called when the player attacks the enemy. To do this, we will need to call the function that inflicts damage on the enemy character from the player management script.


using UnityEngine;

public class Player : MonoBehaviour
{
    public float damage = 20f; // Attack power
    public GameObject enemy; // Reference to the enemy character object

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // Attack with spacebar
        {
            AttackEnemy();
        }
    }

    private void AttackEnemy()
    {
        if (enemy != null)
        {
            enemy.GetComponent().TakeDamage(damage); // Deal damage to the enemy
        }
    }
}

6. Displaying Enemy Character Health in UI

To visually display the enemy's health in the game, we can add a UI element. Unity allows for easy implementation of health bars using its UI system. Proceed with the steps below.

  1. Right-click in the Hierarchy window and select ‘UI’ > ‘Canvas’ to add a canvas.
  2. Right-click within the Canvas and select ‘UI’ > ‘Slider’. This slider will act as the health bar.
  3. Change the `Name` of the slider to ‘HealthBar’ and set the slider value to start from 1.

Then, add a method to update the health bar in the `Enemy` script.


using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour
{
    public float maxHealth = 100f; 
    private float currentHealth; 
    public Slider healthBar; // Health bar slider

    void Start()
    {
        currentHealth = maxHealth; 
        if (healthBar != null)
        {
            healthBar.maxValue = maxHealth;
            healthBar.value = currentHealth;
        }
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage; 
        Debug.Log($"Enemy took {damage} damage. Current health: {currentHealth}");

        if (healthBar != null)
        {
            healthBar.value = currentHealth; // Update health bar
        }

        if (currentHealth <= 0)
        {
            Die(); 
        }
    }

    private void Die()
    {
        Debug.Log("Enemy died."); 
        Destroy(gameObject); 
    }
}

7. Testing the Enemy Character Health System

All settings are complete. Now let’s test the game to see if the enemy character health system works correctly.

  1. Click the Play button at the top of Unity to run the game.
  2. The Cube set as the enemy character should be visible on the game screen.
  3. Press the Space key to inflict damage on the enemy and check that the health bar updates.
  4. Check that when the enemy’s health reaches zero, the enemy dies and disappears.

8. Implementing Additional Features

Although the basic health system implementation is complete, you can enhance it with additional features to create a more polished health system. For example:

  • Add different types of enemy characters: Introduce enemy characters with various maximum health and damage values to increase the game's diversity.
  • Health recovery system: Create enemy characters that recover health over time.
  • Death animation: Add an animation when the enemy character dies to enhance immersion.
  • Sound effects: Add sound effects when the enemy takes damage or dies to improve the game's quality.

9. Conclusion

In this tutorial, we learned how to manage the health of enemy characters in Unity. The health system is simple but essential to the game, and by implementing it properly, you can enhance the fun and challenge of the game. Expand the system with additional features and create your unique game. Game development using Unity offers limitless possibilities, and your creativity will be your most valuable asset.

Don’t be afraid to take your first steps into the world of game development. As you accumulate small successes and gain experience, you will be able to successfully lead larger projects in the future. I hope you continue to practice and deepen your learning based on what you learned in this tutorial today.

Basic Unity Course: Network Environment and Photon Installation

Setting up the network environment in game development is a very important process. Among them, Unity supports various networking solutions, one of which is Photon. Photon is a powerful framework for real-time multiplayer games, characterized by outstanding performance and ease of use. In this article, we will start with the basics of Unity, explain the understanding of the network environment, and describe the process of installing Photon in detail.

1. Basics of Unity

1.1 What is Unity?

Unity is a cross-platform game engine used to create 2D and 3D games. Thanks to its user-friendly interface and powerful features, it is one of the most widely used game development tools worldwide. Using Unity, you can develop and distribute games across various platforms (PC, mobile, consoles, etc.).

1.2 Understanding the Unity Interface

The Unity interface consists of several windows. The main components are as follows:

  • Scene View: This is the space where you can place and manipulate game objects in a 3D or 2D environment.
  • Game View: It reproduces the configured scene exactly as it is in the game, allowing you to check the game being played.
  • Hierarchy: This displays all game objects in the scene in a tree format.
  • Inspector: This is the space where you can modify the properties of the selected game object.

1.3 Scripting Basics

The scripting language used in Unity primarily is C#. C# is an object-oriented programming language that allows you to write complex game logic efficiently. A basic script has the following structure:

using UnityEngine;

public class MyFirstScript : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Hello, Unity!");
    }

    void Update()
    {
        // Called every frame
    }
}

Scripts can be attached to game objects in Unity to define behaviors.

2. Understanding the Network Environment

2.1 The Necessity of Networked Games

Multiplayer games enable interaction between players and increase the fun factor of the game. Therefore, building a network environment is an essential element of game development. There are various forms of network structures such as server-client models and P2P models, each with its advantages and disadvantages.

2.2 Server-Client Model

The server-client model is a structure where the main server manages all game data, and clients request and receive this data. The advantage of this model is that it increases the reliability and consistency of the data. However, it also brings the disadvantage of higher dependence on the server.

2.3 P2P Model

The P2P (Peer to Peer) model is a model where each client is directly connected to perform data communication. This method can reduce server costs, but there may be challenges in maintaining data consistency.

2.4 Network Protocols

In network games, mainly two protocols are used: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). TCP guarantees the reliability of data transmission, while UDP prioritizes fast data transmission. Depending on the type of game, the appropriate protocol should be selected.

3. Installing Photon

3.1 What is Photon?

Photon is a powerful networking solution for multiplayer games that enables real-time communication. It integrates easily with Unity and is used by many developers.

3.2 Steps to Install Photon

To install Photon, follow these steps:

  1. Download Photon Engine: Download the latest version from the official Photon Engine website.
  2. Open Unity Project: Launch Unity and create a new project.
  3. Use Package Manager: Open Unity’s Package Manager, select ‘Add package from git URL…’, and input the copied Photon package URL.
  4. Configure Photon: After installing Photon, you need to set up the Photon Server Settings. Create an Application ID in the Photon Dashboard and enter that ID in Unity.

3.3 Using Photon SDK

The Photon SDK allows you to implement networking features in your game through various APIs. The basic connection code is as follows.

using Photon.Pun;

public class NetworkManager : MonoBehaviour
{
    void Start()
    {
        PhotonNetwork.ConnectUsingSettings();
    }

    void OnConnectedToMaster()
    {
        PhotonNetwork.JoinLobby();
    }
}

3.4 Key Features of Photon

  • Room Management: You can create and manage individual spaces where users can play the game.
  • RPC (Remote Procedure Call): You can call methods on other clients to update the game state.
  • Synchronization through Network Variables: You can easily synchronize the states of various game objects.

3.5 Example of Using Photon

Let’s look at a simple example of how to use Photon in a real game. The following code shows the process of creating a player.

using Photon.Pun;

public class PlayerController : MonoBehaviourPunCallbacks
{
    void Start()
    {
        if (PhotonNetwork.IsConnected)
        {
            PhotonNetwork.Instantiate("PlayerPrefab", Vector3.zero, Quaternion.identity);
        }
    }
}

4. Conclusion

Through the basic Unity tutorial and the installation process of Photon, you can understand and establish a basic network environment. Based on this, you can lay the groundwork for developing multiplayer games. I hope this tutorial helps you appreciate the appeal of network games and encourages you to challenge yourself in actual game development.