Building a Simple 3D Game in Unity

Transitioning from 2D to 3D game development in Unity opens up a world of possibilities. In this tutorial, we'll create a basic 3D game covering environment setup, player controls, object spawning, and game mechanics.

Creating a 3D Environment

Let's start by setting up our 3D project:

  1. Open Unity Hub and create a new project using the "3D" template
  2. Name your project (e.g., "Simple3DGame")
  3. Once loaded, set up your initial scene:

Basic Scene Setup

1. Right-click in Hierarchy → 3D Object → Plane (name it "Ground")
2. Right-click → 3D Object → Cube (name it "Player")
3. Right-click → Create Empty (name it "GameManager")
4. Right-click → Create → Folder (name it "Scripts")

Environment Enhancements

Make your environment more interesting:

1. Add some terrain: Right-click → 3D Object → Terrain
2. Create walls: Duplicate your Ground plane, rotate 90° and position as walls
3. Add lighting: Right-click → Light → Directional Light
4. Add materials to distinguish objects

Player Controller and Camera Movement

3D movement requires different approaches than 2D. Here's how to implement it:

Player Controller Script

Create a new C# script named "PlayerController3D":

using UnityEngine;

public class PlayerController3D : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float rotationSpeed = 100f;
    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // Movement
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        
        Vector3 moveDirection = new Vector3(horizontal, 0, vertical);
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= moveSpeed;
        
        controller.Move(moveDirection * Time.deltaTime);

        // Rotation
        float rotate = Input.GetAxis("Mouse X") * rotationSpeed;
        transform.Rotate(0, rotate * Time.deltaTime, 0);
    }
}

Camera Follow Script

Create a "CameraFollow3D" script for a third-person view:

using UnityEngine;

public class CameraFollow3D : MonoBehaviour
{
    public Transform target;
    public Vector3 offset = new Vector3(0, 2, -5);
    public float smoothSpeed = 0.125f;

    void LateUpdate()
    {
        Vector3 desiredPosition = target.position + offset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.position = smoothedPosition;
        
        transform.LookAt(target);
    }
}

Attach this script to your Main Camera and assign the Player as the target.

Spawning Objects and Obstacles

Dynamic object spawning makes your game more interesting.

Creating Collectible Prefabs

  1. Create a 3D object (e.g., Sphere) for your collectible
  2. Add a Rigidbody component
  3. Create a "Collectible" tag and assign it
  4. Drag it to your Project window to make it a prefab

Object Spawner Script

Create an "ObjectSpawner" script:

using UnityEngine;

public class ObjectSpawner : MonoBehaviour
{
    public GameObject objectToSpawn;
    public float spawnRate = 2f;
    public float spawnRadius = 10f;
    
    void Start()
    {
        InvokeRepeating("SpawnObject", 0f, spawnRate);
    }
    
    void SpawnObject()
    {
        Vector3 spawnPosition = transform.position + Random.insideUnitSphere * spawnRadius;
        spawnPosition.y = 0.5f; // Keep objects above ground
        
        Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);
    }
}

Obstacle Implementation

Create obstacles similarly, but with collision detection:

using UnityEngine;

public class Obstacle : MonoBehaviour
{
    public int damage = 10;
    
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            collision.gameObject.GetComponent<PlayerController3D>().TakeDamage(damage);
            Destroy(gameObject);
        }
    }
}

Adding Win/Lose Mechanics

Complete your game with clear objectives.

Game Manager Implementation

Extend your GameManager script:

using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public Text scoreText;
    public Text healthText;
    public GameObject winPanel;
    public GameObject losePanel;
    
    private int score = 0;
    private int playerHealth = 100;
    public int winScore = 200;
    
    void Awake()
    {
        if (instance == null)
            instance = this;
        else
            Destroy(gameObject);
    }
    
    public void AddScore(int points)
    {
        score += points;
        scoreText.text = "Score: " + score;
        
        if (score >= winScore)
            WinGame();
    }
    
    public void UpdateHealth(int health)
    {
        playerHealth = health;
        healthText.text = "Health: " + playerHealth;
        
        if (playerHealth <= 0)
            LoseGame();
    }
    
    void WinGame()
    {
        winPanel.SetActive(true);
        Time.timeScale = 0f;
    }
    
    void LoseGame()
    {
        losePanel.SetActive(true);
        Time.timeScale = 0f;
    }
}

Player Health System

Modify your PlayerController3D:

public class PlayerController3D : MonoBehaviour
{
    // ... existing code ...
    public int maxHealth = 100;
    private int currentHealth;
    
    void Start()
    {
        // ... existing code ...
        currentHealth = maxHealth;
        GameManager.instance.UpdateHealth(currentHealth);
    }
    
    public void TakeDamage(int damage)
    {
        currentHealth -= damage;
        GameManager.instance.UpdateHealth(currentHealth);
    }
    
    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Collectible"))
        {
            GameManager.instance.AddScore(10);
            Destroy(other.gameObject);
        }
    }
}

Create UI elements for score, health, and win/lose panels to complete your game.

Next Steps

You now have a functional 3D game framework. Consider expanding it by:

  • Adding particle effects for collectibles
  • Implementing enemy AI
  • Creating more complex levels
  • Adding audio effects and background music

3D game development offers endless possibilities - use this foundation to build more sophisticated mechanics as you grow more comfortable with Unity's 3D systems.

Post a Comment

0 Comments