CREA un PERSONAJE COMPLETO en Unity 🎮 (Movimiento, Cámara y Animaciones) 🚀 Curso Paso a Paso

CREA un PERSONAJE COMPLETO en Unity 🎮 (Movimiento, Cámara y Animaciones) 🚀 Curso Paso a Paso

Cómo Animar un Personaje 3D en Unity con Mixamo

Introducción al Tutorial

  • El video presenta un método rápido y gratuito para convertir modelos 3D en personajes animados utilizando Mixamo y Unity, sin necesidad de Blender o rigging manual.
  • Se configurará un sistema de movimiento y una cámara profesional, proporcionando un personaje listo para proyectos personales.

Fuentes de Modelos 3D

  • Se mencionan varias páginas donde se pueden descargar personajes, incluyendo la Asset Store de Unity que ofrece muchos modelos gratuitos.
  • Mixamo es destacado como una herramienta gratuita de Adobe que permite añadir esqueletos y animaciones automáticamente a los personajes 3D.

Creación de Cuenta en Mixamo

  • Para usar Mixamo, se debe crear una cuenta gratuita. Se puede iniciar sesión con Google, Facebook o Apple.
  • En la sección de personajes, se puede elegir entre una variedad disponible; el tutorial usará el personaje "Erica Carter".

Descarga del Modelo

  • Es importante asegurarse de no tener animaciones asignadas antes de descargar el modelo.
  • El formato recomendado para descargar es FBX for Unity, lo cual facilita la importación en Unity.

Importación a Unity

  • Dentro del proyecto en Unity, se crea una carpeta llamada "player" para organizar los modelos importados.
  • Al importar el modelo FBX, es necesario ajustar materiales y texturas para que el personaje luzca correctamente.

Ajustes de Materiales

  • Los materiales pueden requerir ajustes manuales si las texturas no se asignan automáticamente; esto incluye configurar mapas normales y colores base.
  • La configuración del material del pelo debe ser transparente con alpha clipping ajustado para mejorar su apariencia.

Configuración Inicial del Personaje

  • Una vez ajustados los materiales, se arrastra el personaje a la escena y se centra adecuadamente.
  • Se recomienda modificar propiedades como smoothness para evitar un aspecto plástico en los materiales.

Implementación del Movimiento

Añadiendo Suelo y Controlador

  • Se añade un plano como suelo en la escena y se selecciona el personaje para agregarle un componente llamado "character controller".
  • Es crucial ajustar las dimensiones del character controller (radio, altura y posición Y).

Sistema de Input

  • Se utiliza el nuevo sistema de input de Unity añadiendo un componente "player input" al personaje.
  • Duplicar controles predeterminados permite personalizar las entradas sin generar advertencias por uso duplicado.

Programando Movimiento Básico

Creación del Script

  • Un nuevo script llamado "player movement" es creado dentro de una carpeta organizada llamada scripts.
  • Este script necesita referencias al character controller y variables como velocidad e input.

Lógica del Movimiento

  • En el método start se accede al character controller mediante código.
  • Un método on move captura inputs desde teclado o mando para mover al jugador según las teclas presionadas.

Añadiendo Gravedad

Implementando Gravedad

  • Se introduce una variable pública llamada gravity (-9.8), representando la gravedad terrestre.
  • Condicional if verifica si el jugador está en contacto con el suelo antes de aplicar gravedad a su movimiento vertical.

Finalizando Movimiento Vertical

  • La lógica finaliza integrando velocidad vertical junto con movimiento horizontal ya programado; esto asegura que el personaje caiga correctamente cuando salta o cae desde alturas.

Integrando Animaciones

Selección e Importación de Animaciones

  • Desde Mixamo, se busca e importa animaciones específicas (ejemplo: respiración).
  • Las animaciones deben descargarse con skin incluido; luego son organizadas dentro del proyecto bajo carpetas específicas.

Configuración Animator Controller

  • Un animator controller es creado para gestionar transiciones entre diferentes animaciones; inicialmente incluirá solo la animación seleccionada (respiración).
  • Finalmente, este controlador es vinculado al modelo dentro de Unity permitiendo visualizar las animaciones durante la ejecución.

Ajuste Final: Cámara Cinemática

Instalando Cinemachine

  • Para mejorar la experiencia visual, se instala Cinemachine desde Window Package Manager; este paquete simplifica mucho la gestión visual dentro del juego.
  • Una nueva cámara cinemática es creada siguiendo al jugador mediante configuraciones específicas que permiten rotar alrededor del mismo durante su movimiento.

Cinemachine Camera Setup and Character Movement

Setting Up the Cinemachine Camera

  • The camera can be adjusted to follow the character smoothly, allowing for a shoulder view. Users can modify its position for better alignment with the character.
  • Adjustments can be made to the camera's distance and centering, providing flexibility in how it follows the character.
  • The Cinemachine Brain component is added to the main camera, translating virtual cameras into what players see on screen.

Enhancing Character Control

  • The current setup restricts character rotation; adjustments are needed to allow movement in various directions based on camera orientation.
  • A "camera pivot" object is created as an empty game object that will help manage camera rotation relative to the character.

Implementing Camera Rotation Logic

  • The script for managing camera rotation is introduced, which includes references for sensitivity and input handling.
  • Variables are defined for tracking horizontal (yaw) and vertical (pitch) rotations of the camera based on user input.

Character Movement Mechanics

Input Handling for Camera Control

  • An input method is created using Unity's Input System to read mouse movements for controlling camera angles.
  • Horizontal and vertical rotations are calculated based on mouse movement, allowing intuitive control over where the player looks.

Limiting Camera Rotation Angles

  • Vertical pitch angles are clamped between -45° and 60° to prevent unnatural viewing angles beneath or above the character.

Finalizing Camera Functionality

  • The final step involves applying calculated rotations to ensure smooth transitions as users move their mouse, creating a third-person perspective similar to popular games like Fortnite or Zelda.

Player Movement Integration

Structuring Player Hierarchy

  • A clean hierarchy is essential; it consists of a root player object that does not rotate, a pivot that rotates with mouse input, and a visual model that aligns with movement direction.

Transforming Movement Inputs

  • Player movement inputs must be transformed according to camera orientation rather than global axes. This ensures forward motion aligns with where the player is looking.

Smooth Character Rotation Implementation

  • Instead of rotating the entire player object, only the visual model rotates towards movement direction using quaternion interpolation for smoother transitions.

Animation Setup: Walking and Running

Downloading Animations from Mixamo

  • Walk and run animations are sourced from Mixamo. It's crucial these animations do not include positional changes since movement will be handled via code instead.

Animator Configuration in Unity

  • An animator reference is established within scripts alongside boolean variables indicating whether the player is running or moving. Speed parameters are also set up for walking and running states.

Transitioning Between Animations

Animation State Management

  • A method updates animation states based on player movement inputs. Conditions check if characters should transition between idle, walking, or running states depending on speed thresholds.

Animator Controller Setup

  • Parameters such as isMoving and isRunning are added in Unity’s Animator Controller. Transitions between different animation states depend on these parameters being true or false under specific conditions.

Finalizing Player Controls: Sprinting Mechanic

Adding Sprint Functionality

  • A sprint function linked to keyboard input allows players to toggle running speeds easily while maintaining smooth transitions between walking and running animations.

This structured approach provides clarity regarding each aspect of setting up a third-person controller using Cinemachine in Unity while ensuring all key points from your transcript have been captured effectively.

Configuring Animator Parameters for Character Movement

Setting Up Animator Parameters

  • The animator will have parameters to control transitions, including a boolean named grounded to check if the character is on the ground.
  • A float parameter for vertical velocity is needed to manage transitions between being airborne and falling.
  • A trigger parameter for jump will be created, which activates the jump animation immediately upon pressing the jump key.

Implementing Jump Logic in Code

  • A public float variable called jump force is defined to determine how high the character can jump, initially set to five.
  • The method on jump checks if the jump key is pressed and if the character is grounded before executing a jump.
  • Upon jumping, the vertical velocity is set equal to the jump force, and the animator's trigger for jumping is activated.

Finalizing Animation Transitions

Adjusting Animator Settings

  • In Animator settings, a boolean parameter named grounded will indicate whether or not the character is on solid ground.
  • The vertical velocity must be set as a float in the animator controller; case sensitivity in naming parameters is crucial to avoid issues.

Transition Conditions

  • An "Any State" transition allows jumping from any animation state when conditions are met (i.e., when grounded).
  • To transition into falling animations, conditions include being grounded as false and having a vertical velocity less than -0.1.

Managing Animation States

Transition Management

  • Transitions from fall back to walking or hitting states require specific conditions such as being grounded and not moving.
  • The transition speed can be adjusted for smoother animations; removing unnecessary time constraints enhances realism.

Testing Animations

  • After setting up transitions, testing involves selecting player events and linking them with corresponding methods like on jump.

Refining Animation Feel

Adjusting Animation Timing

  • Fine-tuning animation transitions helps achieve desired responsiveness; reducing transition times may enhance gameplay feel.

Experimenting with Different Animations

  • Players are encouraged to experiment with various animations until they find combinations that suit their game's dynamics.

Adding Dance Animations

Integrating Dance Moves

  • New dance animations can be added by importing files into Unity; ensuring they do not loop by default maintains control over playback.

Creating Dance Layers in Animator

  • A new layer named "dance layer" will separate dance logic from other animations; it starts empty until triggered by user input.

Setting Up Dance Triggers

Defining Exit Conditions for Dance Animations

  • Three exit conditions are established: finishing the dance, moving while dancing, or jumping during a dance sequence prevent animation bugs.

Assigning Controls for Dancing

  • Control mappings allow players to initiate dances using keyboard keys or gamepad buttons; this enhances interactivity within gameplay.

Finalizing Character Animation Setup

Testing Complete Functionality

  • After implementing all features, testing ensures that characters respond correctly during jumps and dances without glitches.
Video description

🎮 En este vídeo vas a crear un personaje COMPLETO en Unity desde cero, listo para usarse en cualquier videojuego profesional. Vamos a usar Mixamo, el nuevo Input System de Unity, CharacterController, animaciones humanoides y Cinemachine para construir un sistema de personaje moderno, estable y escalable como los que se usan en juegos reales. 👇Proyectos y Series completas en el PATREON!👇 ✔️Patreon: https://www.patreon.com/luiscanary 📌 En este vídeo aprenderás: ✅ Descargar y preparar personajes desde Asset Store, Fab y Mixamo ✅ Importar modelos 3D correctamente en Unity ✅ Configurar materiales en URP (specular, smoothness, transparencias) ✅ Crear movimiento con CharacterController ✅ Usar el New Input System de Unity ✅ Configurar PlayerInput y eventos ✅ Añadir gravedad y físicas básicas estables ✅ Importar animaciones (idle, walk, run) ✅ Configurar sistema Humanoid y Avatars ✅ Crear Animator Controller profesional ✅ Usar Cinemachine para cámara en tercera persona ✅ Crear cámara dinámica con Camera Pivot ✅ Separar lógica de Player, cámara y visual ✅ Movimiento relativo a la cámara (sistema pro) ✅ Sistema completo de animaciones (idle, walk, run, jump, fall) ✅ Sistema de baile con Animation Layers ✅ Transiciones avanzadas en Animator 🔥 Al final tendrás un personaje totalmente jugable, con cámara, animaciones y control profesional listo para tu videojuego. 🌐 RECURSOS DEL VÍDEO 🛒 Unity Asset Store https://assetstore.unity.com/ 👉 Assets, modelos y recursos oficiales para Unity 🎨 Fab (Epic / Unreal Assets) https://www.fab.com/ 👉 Assets gratuitos y premium para juegos 🧍 Mixamo (Animaciones automáticas) https://www.mixamo.com/ 👉 Personajes + animaciones listas para usar en segundos 🎥 TUTORIALES RELACIONADOS 🧠 Cómo crear personajes desde cero (MakeHuman ) 👉 https://youtu.be/FjV9XRJY1Y0 ⬇️ Cómo instalar Unity paso a paso 👉 https://youtu.be/Ct4l3ILqkxA 🌐 Todos mis enlaces, recursos y proyectos 👉 https://beacons.ai/luiscanary 🎮 Aprende desarrollo de videojuegos ▶️ Unity – https://www.youtube.com/watch?v=zFe77GJs4EQ&list=PLNEAWvYbJJ9nCFX4OPTzdz9gNZTSKOZac 🎓 Cursos de Desarrollo de Videojuegos 👉 Unity 2D – Crea un RPG desde cero: https://www.udemy.com/course/curso-completo-de-unity-2d-desarrolla-un-rpg-desde-cero/?referralCode=565445A20A07B9EF31B6 🌐 Redes y comunidad 📷 Instagram: https://www.instagram.com/luiscanary_/ 🐤 Twitter/X: https://twitter.com/luiscanary 🔴 Twitch: https://www.twitch.tv/luiscanary 🎼 TikTok: https://www.tiktok.com/@luiscanary ✏️ Discord: https://discord.gg/pWf23EH9j4 📘 Facebook: https://www.facebook.com/LuisCanaryy/ ⭐ Contenido ⭐ ⌨️ (00:00:00) Introducción ⌨️ (00:00:33) Descargar O Crear Personaje ⌨️ (00:01:46) Descargar Personaje Mixamo ⌨️ (00:03:33) Configurar Materiales ⌨️ (00:06:42) Añadir Movimiento Personaje ⌨️ (00:14:14) Añadir Gravedad al Personaje ⌨️ (00:16:35) Animación Idle (Respirar) ⌨️ (00:20:45) Ajustar Cámara (Cinemachine) ⌨️ (00:22:52) Rotar Cámara Alrededor Del Personaje ⌨️ (00:28:14) Orientar Personaje Dirección Camara ⌨️ (00:34:10) Añadir Animaciones Walk Y Run ⌨️ (00:43:29) Salto Personaje ⌨️ (00:52:43) Añadir Animación Baile ⌨️ (00:58:02) Conclusión #unity #unity3d #gamedev #desarrollodevideojuegos #indiedev #videojuegos #programacion #unitytutorial #gamedevelopment