Unity Tutorial 4 - Coroutines - Corrutinas

-----------------------------------------------------------------------------------------------------------------
DISCLAIMER - May 2021
These tutorials were written a long time ago. I did some parts of the code literally the day after installing Unity therefore they could be improved or done differently in many ways. Updating them is definitely in my to-do list but right now I'm currently working in other projects so it will take me time. If you think this content is useful you can follow me on my social media to stay tuned.
AVISO - Mayo 2021
Estos tutoriales fueron escritos hace mucho tiempo. Hice algunas partes del código literalmente el día después de instalar Unity por lo que podrían ser mejorados o realizados de otras maneras. Actualizarlos está definitivamente en mi lista de tareas pero ahora estoy trabajando en otros proyectos y me llevará tiempo. Si piensas que este contenido es útil puedes seguirme en mis redes sociales para estar atento.
-----------------------------------------------------------------------------------------------------------------


English
Hi everyone!! In this tutorial we'll finish our small cube game for Unity. Let's begin!

Step #1 Understanding coroutines

I don't want to quote exactly what you can find in the official manual so I will try to use my own words. A coroutine is a function/method that runs separately from the initial code and shows intermediate results before finishing.
In our case, we want to move a box 90 degrees in the space. What the code does, is turn the corresponding face small turns immediately and make a short pause between them so the final result looks like it has turned 90 degrees at constant angular speed in half a second.
At this point, it's important to understand the Time.deltaTime concept, which was introduced in the second tutorial. Depending on the device we are playing our game in, it will show more or less frames per second. Moreover, even in the same device that ratio is not constant. It depends on a lot of factors. Time.deltaTime returns the time that has passed between the last two frames. When the box is making a pause, we can use Time.deltaTime to know exactly when the exact time to move again has come. The coroutine would be like this:
We have to declare the rotating variable before the start method:

Step #2 Update turnface method. Visibility of the GameObjects

All we have to do now is update a few things in the turnface method we created in the third tutorial. 










There are basically two changes. The first one was moving the part where the hierarchy is cancelled to the coroutine. It's very important to do this because otherwise that part will be reached before the object has finished its movement and the result will be quite chaotic. The second change was disabling the visibility of the faces that we don't need in the movement but are occupying that space.

Step #3 Extra

The game has already finished. One last thing that we could add would be text labels in space to identify the faces of the cube. It's optional, you don't really need it to play. It's not something worth explaining. If you do it and you want the result to be better you could import TextMeshPro package. It's really easy at this point.

That was the end of this Unity Tutorial series for now (if I find something interesting or if people ask me to continue, I will continue). You can read my last tutorials here:



Tutorial 1 - Light, color, materials
https://www.curiousruben.com/2020/07/unity-tutorial-1-creating.html
Tutorial 2 - Camera
Tutorial 3 - Hierarchy, input, code

Bye!!




Español

¡¡Hola a todos!! En este tutorial acabaremos acabaremos nuestro juego del cubo pequeño para Unity. ¡Empecemos!

Paso nº1 Entender las corrutinas

No quiero citar exactamente lo que podéis encontrar en el canal oficial así que intentaré usar mis propias palabras.Una corrutina es una función/método que se ejecuta separadamente del código inicial y que muestra resultados intermedios antes de acabar
En nuestro caso, queremos mover una caja 90 grados en el espacio. Lo que hace el código, es girar la cara correspondiente pequeños giros instantáneamente y hacer una pausa pequeña entre ellos para que el resultado final parezca que ha girado 90 grados a velocidad angular constante en medio segundo.
En este punto, es importante entender el concepto Time.deltaTime que fue introducido en el segundo tutorial. Dependiendo del dispositivo en el que estemos jugando nuestro juego, se mostrarán más o menos fotogramas por segundo. Además, incluso en el mismo dispositivo, esa relación no es constante. Depende de muchos factores. Time.deltaTime devuelve el tiempo que ha pasado entre los dos últimos fotogramas. Cuando la caja está haciendo una pausa, podemos usar Time.deltaTime para saber exactamente cuándo ha llegado el momento de moverse otra vez. La corrutina quedaría así:
Tenemos que declarar la variable "rotating" antes del método start:

Paso nº2 Actualizar el método turnface. Visibilidad de los objetos

Todo lo que nos queda por hacer ahora es actualizar el método turnface que creamos en el tercer tutorial. 










Hay básicamente dos cambios. El primero ha sido mover la parte en la que la jerarquía es cancelada a la corrutina. Es muy importante hacer esto porque, de otra manera, esa parte será alcanzada antes de que el objeto haya terminado su movimiento y el resultado será bastante caótico. El segundo cambio fue anular la visibilidad de las caras que no necesitamos en el movimiento pero ocupan ese espacio.

Paso nº3 Extra

El juego ya ha acabado. Una última cosa que podríamos añadir sería etiquetas de texto en el espacio para identificar las caras del cubo. Es opcional, no lo necesitáis para jugar. No es algo que merezca la pena explicar. Si lo hacéis y queréis que el resultado sea mejor, podéis importar el paquete TextMeshPro. En este punto es muy fácil.

Este es el final de esta serie de tutoriales de Unity por ahora (si encuentro algo interesante o si la gente me pide que continue, continuaré). Podéis leer mis últimos tutoriales aquí:



Tutorial 1 - Light, color, materials
https://www.curiousruben.com/2020/07/unity-tutorial-1-creating.html
Tutorial 2 - Camera
Tutorial 3 - Hierarchy, input, code

¡¡Adiós!!

Comments

  1. What exactly do i have to do so the black faces dont take one complete turn while the corners only move a little

    ReplyDelete
    Replies
    1. The corners move the same angle as the face they are children of. What I think you see, is part of the other
      black faces that are in the same space as the face you are turning. That's why I turn off the visibility
      of those faces before the turn begins:
      face.GetComponent().enabled=false;
      .
      .
      When the movement has finished, I set that value back to true for all faces.

      I hope this can help you ;)

      Delete
  2. Thanks a lot. Sorry for leaving a reply, should've jsut commented once again. So the problem i am now facing, is that, the face i choose does the constant rotation i want it to while the corners only perform a rotation of 1/9 of the intended angle. I seriously have no clue why it doesn't work,

    ReplyDelete
    Replies
    1. At the beginning of the function "turnface" the code makes the corners that are going to move, children of the face that is moving. At the end, this is undone again:
      ...
      auxA.transform.parent=null;
      ...

      it's important that you make sure you have these lines at the end of the coroutine, after the 2 while loops. You probably have them in the function so the code reaches the part where the corners stop being children of the face while the coroutine is still running.

      Good luck!

      Delete

Post a Comment