El personaje y el controlador

1

Introducción: De la idea al desarrollo

2

Estructura de carpetas en Unity

3

Assets, Game Objects y Sprite Atlas

4

Animaciones desde un sprite map

5

Animation Controller y Transiciones

6

Plataformas y gravedad

7

Física en Unity

8

El script de control

9

Programando funciones en C# y Unity: Jump

10

Detectar el suelo con Raycast

11

Herramientas de debugging visual

12

Cambiar las animaciones según los estados

13

Reto: Terminando nuestras animaciones

14

Solución del reto

15

Hacer que el personaje camine

El manager del videojuego

16

Cómo funciona el Game Manager

17

El Singleton

18

El modo de juego

19

Input manager y juegos multiplataforma

20

Corrección del Bug del salto

21

La zona de muerte

22

Reiniciar la partida

23

Corrigiendo los bugs al reiniciar nuestro juego

Diseño procedural de niveles 2D

24

El diseño de niveles a mano

25

Configurando nuestros assets para el diseño procedural

26

Generación procedural de niveles

27

Creando la zona que eliminará bloques del nivel excedentes

28

Añadir un nuevo bloque de forma aleatoria

29

La cámara que sigue al jugador

30

Destrucción de bloques antiguos

31

Terminando de programar la destrucción de bloques antiguos

32

Solucionando el salto de la cámara al reiniciar el juego

HUD, menús y gameplay

33

El canvas en Unity

34

Uso de botones para crear un menú

35

La lógica de los menús

36

Ejercicio: Preparando el menú del juego

37

Programando el menú del juego

38

Los coleccionables del juego

39

Actualizar UI de coleccionables

40

Iniciando con pociones y maná

41

Pociones de vida y maná

42

Programando las barras de vida y maná

43

Calculando los puntajes con la distancia y el tiempo de juego

44

La lógica del maná

Enemigos y dificultad

45

Plataformas móviles

46

Iniciar movimiento de la plataforma con trigger

47

Enemigos móviles

48

Enemigos móviles: preparando nuestro enemigo para girar

49

Enemigos móviles: programando que gire al chocar

50

Arreglando el collider de nuestra roca

51

Programando la condición de muerte del personaje

52

Añadiendo música de fondo a nuestro videojuego

53

Añadiendo efectos de sonido y cierre del curso

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
10 Hrs
57 Min
11 Seg
Curso de C# para Videojuegos

Curso de C# para Videojuegos

Juan Gabriel Gomila

Juan Gabriel Gomila

Enemigos móviles: programando que gire al chocar

49/53
Resources

How to improve enemy behavior in a video game?

Video game development is an art that combines creativity and technical knowledge. When it comes to designing a video game in which enemies interact with the environment, it is essential that their behavior is intuitive and realistic. In this section, we will explore a strategy to improve the behavior of an enemy by using collisions with objects on the stage to automate its turning and keep it within a given area.

How to use rocks as collision elements?

Rocks and other environmental elements can play a crucial role in the dynamics of a video game, serving as obstacles that interact with characters. To implement this:

  1. Add rocks to the scenery: prefabs can be used to add rocks to the video game environment. It is important to position them strategically and adjust their size as needed.

  2. Configure your collider: Make sure the rock's collider is configured to allow the character to jump over it, without going through it. This is accomplished by using the terrain layer that prevents characters from traversing the ground.

  3. Strategic placement: Placing the rocks so that the enemy bounces between them keeps the enemy within a specific area of the level, thus preventing them from straying from the desired area.

How to implement enemy collisions?

Implementing collisions in the enemy script can transform how the enemy interacts with the environment. To do so, follow these steps:

  1. Collision script: You must modify the enemy script to handle collisions using the OnTriggerEnter2D method. This method will detect when the enemy comes in contact with any other object with a collider.

    void OnTriggerEnter2D(Collider2D collision) { Debug.Log(collision.tag); // Show the tag of the object it collides with if (collision.tag == "Player") { // Logic to affect the player } else if (collision.tag == "Coin") { return; // Do nothing if it collides with a coin } else { // Change the direction of the enemy if it collides with the stage facingRight = !facingRight; } }}
  2. Interaction according to the type of collision: Depending on the tag of the object with which it collides, the appropriate behavior must be programmed:

    • With the player: decrease the life bar.
    • With coins: Ignore the collision.
    • With the scenario: Change the direction of movement.

How to adjust the player damage logic?

Player damage is a fundamental aspect of balancing the game. The approach here should be clear and flexible:

  1. Using configurable variables: declaring a public variable for the damage inflicted by the enemy allows to modify this value from the Unity editor.

    public int enemyDamage = 10; // Damage the enemy inflicts on the player.
  2. Implementation in the code: inside the enemy script, when detecting a collision with the player, the CollectHealth method of the player script must be invoked to adjust its life bar:

    player.GetComponent<PlayerController>().CollectHealth(-enemyDamage);

What to do when scenario or player is not affected?

When the enemy collides with an object that is not significant in the game (such as coins), it is crucial to optimize the behavior so as not to waste resources on unnecessary actions:

  • Immediate return: in the face of irrelevant collisions, the action should be to simply return before processing unnecessary additional logic.

How to integrate collision and animation for enhanced visual effect?

The key to achieving convincing enemy behavior is to properly combine physics with animations. Correctly adjusting enemy rotations and state ensures a smooth and natural transition of movement.

  • Control variable: Use a boolean variable to determine the direction in which the enemy should be facing.

    facingRight = !facingRight; // Reverses direction when colliding.
  • Fixed-time update: Rotation should be handled within a FixedUpdate method, resulting in a smooth, gradual change of direction, noticeable to the player.

As you advance in game development, these techniques will allow you to interact in a more complex way with the environment, improving not only the gameplay but also the aesthetics of the game. With each tweak to the game mechanics, you will shape a more engaging and dynamic virtual world. Keep learning and honing your development skills!

Contributions 11

Questions 4

Sort by:

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

tengo un problema con el prefab del enemigo, es que cuando uno el prefab del Level_Block_0 con el del enemigo y le doy guardar cambios psss a la final no me guarda correctamente porque le doy al simulador y el enemigo me sale en una cordenada distinta a la que le coloque, pense que era problema del prefab del enemigo asi que la borre y la hice denuevo pero a la final vuelve a pasar D= que hago ???

Un detalle que no se mencionó, me di cuenta en mi juego que por como está programado, los enemigos rebotan con las Exit Zone, por lo que tuve que agregar un nuevo Tag para éstas y en el código las coloqué de la siguiente manera:

        if(collision.tag == "Coin" || collision.tag == "ExitZone")
        {
            return;
        }```

Con eso evitamos el WTF que en el juego veamos al enemigo cambiar de sentido porque si.

En el título dice fire en vez de gire, se entiende pero sugiero cambiarlo 😃

Otra forma de que el enemigo gire es con:

if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
        {
            facingRight = !facingRight;
        }

Personalmente preferí esta forma a la del profesor ya que aquí específicamente realiza su acción con aquellos que estan en el layer “Ground” (si en algún futuro queremos crear otra etiqueta que no sea coin o player, con el método del profe girarían al chocar por la forma en que se programó. De hecho a algunos ya les giraba con elementos como el exit zone)

Agregué el TAG de “Coin” a las pociones para que pasara por encima en ese caso también, claro otra opcion seria colocarle diferente TAG (o cambiarlo por “collectables”?) para lograr el mismo efecto.

Si a alguien le sirve, yo le agregue 2 condicionales dentro de las condicionales para que según la distancia cambie su movimiento sin necesidad de hacer colisión con algo mas.

Hola, al menos en este momento, el orden de esta clase y algunas de las que sigue parece estar mal, en esta clase ya está armado el script del enemigo y no se muestra cuando este de hizo, por lo que revisé y vi que deberíamos ver, por lo menos, las dos próximas clases antes que esta. Por lo que, amenos que corrijan el orden, deberíamos saltearnos esta clase para volver más tarde. Saludos!

Me parece que este capitulo 46 debe ir después del 49?

Que importante es la nomenclatura en C# por favor. Mi enemigo colisionaba con la moneda, revisando el código me di cuenta que en el condicional de la colisión con la moneda, no escribí coin con C mayúscula, por lo tanto mi enemigo pasaba del tema y chocaba con ella.

Podria haber quedado con un CASE??

Colisión enemigo

https://drive.google.com/file/d/1ZL8H9-AEdcyQ7yIvj9dHB8j80B5W3CBX/view?usp=sharing```