Introducci贸n

1

Game Design del juego

2

La estructura y assets de un proyecto en Unity

3

Convirtiendo nuestros assets en Tiles

4

Tilemaps y creaci贸n del escenario

5

Bonus: FastForward de la creaci贸n del escenario, sorting layers y creaci贸n de colliders

6

Ac谩 encontrar谩s los archivos de este curso

Personaje principal: Movimiento y Animaciones

7

El jugador y el movimiento

8

Creando nuestra primera animaci贸n

9

Creando el grafo de animaciones

10

Usando un 谩rbol de animaciones

11

Mostrando la soluci贸n del desaf铆o e implementando transici贸n entre blended trees

12

Programando una c谩mara que siga al jugador

13

Correcci贸n del bug gr谩fico

14

l铆mites del escenario, rigid bodies

15

Ejercicio: dise帽o de interiores

Escenarios Avanzados

16

Transiciones entre escenas

17

Mantener Player y Camera entre escenas

18

Spawning Points: programando que el jugador y la c谩mara aparezcan en el lugar correcto al cambiar de escena

19

Agregando Identificadores a nuestros Spawning Points para controlar mejor el flujo de nuestro juego

Enemigos Avanzados

20

Creando nuestro enemigo

21

Programando las f铆sicas y el patrullaje del enemigo

22

Generando movimiento completamente aleatorio

23

Programando el ataque del enemigo

24

Crear Manager de Health del Player

25

Crear armas

26

Programando el ataque del Player con arma

27

Mover la espada al caminar

28

Creando el ataque con espada

29

Ejecutando el ataque con un bot贸n

30

Movimiento en diagonal

31

Optimizando nuestro player controller

32

Ataque mejorado

33

Uso de part铆culas

34

A帽adir el da帽o del enemigo en batalla

35

Programando los contadores de vida del enemigo

36

Colocando m谩s info de UI en pantalla

37

Script de la vida

Personaje principal avanzado

38

A帽adir el da帽o del personaje (ejercicio)

39

Sistema de puntos de experiencia para nuestro personaje principal

40

Level Up!

41

Level Up! Defensa y Reto Final del M贸dulo: Stats de los enemigos

42

Creando un NPC

43

Limitar el movimiento de nuestro NPC

44

Creando una pantalla de di谩logos para nuestro RPG

45

El di谩logo del NPC

46

M煤ltiples l铆neas de di谩logo

47

Parar el NPC durante el di谩logo

48

Parar el personaje durante el di谩logo

Quests

49

La estructura de una quest

50

Quest 1: Ir a un lugar

51

Quest 2: Encontrar un objeto

52

Quest 3: Matar enemigos

53

Revisi贸n de bugs

54

Mantener la c谩mara dentro del escenario

55

El problema al cambiar de escena

Audio

56

Agregando SFX a nuestro videojuego

57

Agregando m煤sica a nuestro videojuego

58

Ajustar vol煤men del audio de cada uno de los efectos de sonido

59

Creando un VolumeManager

60

Agregando econom铆a a nuestro juego y cierre

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
9 Hrs
18 Min
2 Seg

Ejecutando el ataque con un bot贸n

29/60
Resources

How to synchronize attacks and movement in a video game?

In video game development, synchronizing attack and movement animations is crucial to provide a smooth and dynamic experience. This article discusses how to implement such functionality using Animator and controllers. By following these steps, developers can ensure that their characters not only move, but also change state appropriately when attacking, providing more realistic and immersive gameplay.

How to link the controller to the Animator?

To begin with, it is essential to establish a clear connection between the player's controller and the Animator in Unity. This is achieved by assigning appropriate states and conditions that allow switching between movement and attack animations.

  • Define constants and variables: enter private const string attackingState for the attacking state, ensuring that its name exactly matches the state of the Animator, in this case, "attacking".

  • Manage the attack state: create variables such as private bool attacking, private float attackTime, and public float attackTimeCounter to manage the attack duration and state.

  • Synchronization with Update: insert logic in the Update function to coordinate movement and attack, defining when a character should stop moving during the attack.

    private bool attacking = false; private float attackTime; public float attackTimeCounter;

    // Dentro de la función Update if (attacking) { attackTimeCounter -= Time.deltaTime; if (attackTimeCounter < 0) { attacking = false; animator.SetBool(attackingState, false); } } else { // Todo el código relacionado con el movimiento va aquí }

How to implement the button-press attack?

User interaction must be clear and direct. In many games, the left mouse click is often used to trigger the attack.

  • Detect mouse input: use Input.GetMouseButtonDown(0) to detect the left click.

  • Adjust the attack state: change the variables needed to start the attack and stop the character's movement.

  • Reset the attack counter: reset attackTimeCounter to the value of attackTime to prepare for the next attack.

    if (Input.GetMouseButtonDown(0)) { attacking = true; attackTimeCounter = attackTime; player.rigidbody.velocity = Vector2.zero; // Stop the character animator.SetBool(attackingState, true); }

What common errors can we encounter and how to fix them?

Sometimes, problems can arise that prevent the attacking state from being triggered correctly. It is essential to review the code to find solutions.

  • Verification of names: make sure that the names of variables and constants match exactly those used in the Animator.
  • Variable control: check if the private and public variables are assigned correctly, making sure that attackTime is public if we want to configure it from the Unity editor.
  • Console check: observe messages and warnings in the Unity console to identify possible implementation errors.

In case animations are not triggered, it might be necessary to check that the Animator is configured correctly and review the control script.

Why adjust animation and control to improve gameplay?

The balance between short animations and attack times is crucial. An incorrect duration can lead to a frustrating gameplay experience.

  • Adapt the sword or weapon: in games where precision is key, it is possible to consider extending the weapon's range to facilitate gameplay.
  • Synchronize attack time with animation: ensure that the duration of the attack matches that of the animation so that the avatar performs complete and effective actions.

Properly animating and adjusting attack movement in a video game not only improves player interaction, but also adds a level of depth and realism that can make a big difference in user satisfaction. With the right approach, developers can create much more dynamic and engaging gameplay experiences.

Contributions 7

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Excelente clase, es muy bueno que en todo el curso ir saltando de programar a animar, porque as铆 vamos viendo como es que realmente es que se desarrollo un videojuego en la vida real, y ademas hace las clases mas din谩micas.
Adem谩s de que el profesor es incre铆ble.馃挌馃槃

Atacando a diestro y sinistro:

He logrado hacer que el bast贸n lance una bolita que hace da帽o, y solo cuando se tiene el bast贸n equipado

asi explicado el codigo es mas facil de entender

Genial

Yo puse las funciones despu茅s de invocar la funci贸n de caminar para poder moverme despu茅s de atacar y quite el playerRigidbody.velocity.zero, para que no se frene y la verdad es que es muy 煤til.

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

public class PlayerMovement : MonoBehaviour
{

    public float speed = 2.5f;
    private bool IsWalking = false;
    public Vector2 lastMovement = Vector2.zero;

    private const string horizontal = "Horizontal";
    private const string vertical = "Vertical";
    private const string lastHorizontal = "LastHorizontal";
    private const string lastVertical = "LastVertical";
    private const string isWalkingState = "IsWalking";
    private const string attackingState = "Attacking";

    private Animator animator;
    private Rigidbody2D playerRb;

    public static bool playerCreated;

    public string nextPlaceName;

    private bool attacking = false;
    public float attackTime;
    private float attackTimeCounter;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
        playerRb = GetComponent<Rigidbody2D>();
        if (!playerCreated)
        {
            playerCreated = true;
            DontDestroyOnLoad(this.transform.gameObject);
        }else
        {
            Destroy(gameObject);
        }
    }

    // Update is called once per frame
    void Update()
    {
        // s = v*t;
        IsWalking = false;

            if (Mathf.Abs(Input.GetAxisRaw(horizontal)) > 0.5f)
            {
                /* this.transform.Translate(new Vector3(Input.GetAxisRaw(horizontal) * speed * Time.deltaTime, 0, 0)); */
                playerRb.velocity = new Vector2(Input.GetAxisRaw(horizontal) * speed * Time.deltaTime, playerRb.velocity.y);
                IsWalking = true;
                lastMovement = new Vector2(Input.GetAxisRaw(horizontal), 0);
            }
            else
            {
                playerRb.velocity = new Vector2(0f, playerRb.velocity.y);
            }

            if (Mathf.Abs(Input.GetAxisRaw(vertical)) > 0.5f)
            {
                /* this.transform.Translate(new Vector3( 0, Input.GetAxisRaw(vertical) * speed * Time.deltaTime, 0)); */
                playerRb.velocity = new Vector2(playerRb.velocity.x, Input.GetAxisRaw(vertical) * speed * Time.deltaTime);
                IsWalking = true;
                lastMovement = new Vector2(0, Input.GetAxisRaw(vertical));
            }
            else
            {
                playerRb.velocity = new Vector2(playerRb.velocity.x, 0f);
            }

        if (!IsWalking)
        {
            playerRb.velocity = Vector2.zero;
        }

        if (Input.GetKey(KeyCode.Z))
        {
            attacking = true;
            attackTimeCounter = attackTime;
            animator.SetBool(attackingState, true);
        }

        if (attacking)
        {
            attackTimeCounter -= Time.deltaTime;
            if (attackTimeCounter < 0)
            {
                attacking = false;
                animator.SetBool(attackingState, false);
            }
        }

        animator.SetFloat(horizontal, Input.GetAxisRaw(horizontal));
        animator.SetFloat(vertical, Input.GetAxisRaw(vertical));

        animator.SetBool(isWalkingState, IsWalking);

        animator.SetFloat(lastHorizontal, lastMovement.x);
        animator.SetFloat(lastVertical, lastMovement.y);
    }
}

Hola tengo un bug y es que cuando intento de atacar hacia la izquierda ataca hacia la derecha alguien sabe como corregir esto?