Tutorial Tetris en Unity (Parte 4): Spawner, Game Loop y Puntuaciones

Tutorial Tetris en Unity (Parte 4): Spawner, Game Loop y Puntuaciones

Cómo Crear un Juego de Tetris en Unity
(Parte 4: Spawner, Game Loop y Puntuaciones)

¡Llegamos a la última parte de nuestra serie! Ya tenemos el tablero, las piezas y el fantasma. Ahora vamos a programar el sistema de aparición aleatoria (`Spawner.cs`) y el controlador maestro de la partida (`GameController.cs`) que gestiona el tiempo, la entrada del usuario y los puntos.

1. El Generador de Piezas (`Spawner.cs`)

Este script se encarga de contener un array con los prefabs de todos los tetrominos (I, J, L, O, S, T, Z) y generar uno aleatorio en la parte superior del tablero cada vez que la pieza actual se fija.

using UnityEngine; public class Spawner : MonoBehaviour { public Shape[] allShapes; public Shape SpawnShape() { int i = Random.Range(0, allShapes.Length); if (allShapes[i] != null) { Shape shape = Instantiate(allShapes[i], transform.position, Quaternion.identity); return shape; } return null; } }

2. El Bucle Principal y Control de Juego (`GameController.cs`)

El controlador es el cerebro del juego. Detecta las teclas de flecha para mover y rotar la pieza, gestiona la velocidad de caída automática y comprueba las condiciones de Game Over si las fichas superan el límite superior del tablero.

3. Código C# Completo: `GameController.cs`

Crea un script llamado GameController.cs y pega el siguiente código optimizado:

using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { private Board gameBoard; private Spawner shapeSpawner; private Ghost ghost; private Shape activeShape; public float fallInterval = 0.8f; private float fallTimer; private bool isGameOver = false; void Start() { gameBoard = Object.FindFirstObjectByType(); shapeSpawner = Object.FindFirstObjectByType(); ghost = Object.FindFirstObjectByType(); if (shapeSpawner) { activeShape = shapeSpawner.SpawnShape(); } } void Update() { if (isGameOver || gameBoard == null || shapeSpawner == null) return; PlayerInput(); DrawGhostPiece(); } void PlayerInput() { if (Input.GetKeyDown(KeyCode.LeftArrow)) { activeShape.MoveLeft(); if (!gameBoard.IsValidPosition(activeShape)) activeShape.MoveRight(); } else if (Input.GetKeyDown(KeyCode.RightArrow)) { activeShape.MoveRight(); if (!gameBoard.IsValidPosition(activeShape)) activeShape.MoveLeft(); } else if (Input.GetKeyDown(KeyCode.UpArrow)) { activeShape.Rotate(); if (!gameBoard.IsValidPosition(activeShape)) activeShape.UndoRotate(); } else if (Input.GetKeyDown(KeyCode.DownArrow) || Time.time - fallTimer >= fallInterval) { activeShape.MoveDown(); if (!gameBoard.IsValidPosition(activeShape)) { activeShape.MoveUp(); LandShape(); } fallTimer = Time.time; } } void LandShape() { gameBoard.StoreShapeInGrid(activeShape); StartCoroutine(gameBoard.ClearAllRows()); if (gameBoard.IsOverLimit(activeShape)) { GameOver(); return; } activeShape = shapeSpawner.SpawnShape(); fallTimer = Time.time; } void DrawGhostPiece() { if (ghost && activeShape) { ghost.DrawGhost(activeShape, gameBoard); } } void GameOver() { isGameOver = true; if (ghost) ghost.Reset(); Debug.Log("¡Juego Terminado!"); // Opcional: Cargar escena de Game Over // SceneManager.LoadScene(SceneManager.GetActiveScene().name); } }

¡Felicidades!

Con esta cuarta parte ya tienes toda la arquitectura de scripts necesaria para ensamblar tu propio clon de Tetris funcional y optimizado en Unity. ¡Es hora de lucirlo en tu blog Videojuegos Unity Jr.!

Aqui tiene el enlace al PDF con los 13 scripts de Tetris

© 2026 Videojuegos Unity Jr. - Creado por Juan Rafael.

Comentarios