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
isMovingandisRunningare 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
groundedto check if the character is on the ground.
- A float parameter for
vertical velocityis needed to manage transitions between being airborne and falling.
- A trigger parameter for
jumpwill be created, which activates the jump animation immediately upon pressing the jump key.
Implementing Jump Logic in Code
- A public float variable called
jump forceis defined to determine how high the character can jump, initially set to five.
- The method
on jumpchecks 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
groundedwill 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.