lunes, 13 de junio de 2016

Como crear un botón de pausa | How to create a pause button

Español | English

Los botones de pausa son fundamentales para los videojuegos, son una herramienta que no puede faltar en cualquier juego sin importar en que medio se este jugando. Por eso hoy voy a crear un simple tutorial para crear un botón de pausa en Unity.

Si bien yo creo que cada juego debería ser analizado individualmente dependiendo de sus características, lo que principalmente buscamos es crear un estado en donde toda actividad se detiene. Lo que más en detalle vamos a hacer sería detener el tiempo, ya que muchas funciones dependen de el para funcionar.

Como no todas las mecánicas del juego dependen del tiempo (como el desplazamiento de un objeto que recibe un Input como el teclado), estas van a seguir activas mientras el tiempo este detenido, de ahí que digo que cada juego puede utilizar mecánicas especiales y por eso debe ser pensado distinto.

Primero en principal debemos crear un botón de GUI: 


Ahora creamos el Script (o usamos uno ya existente) en donde vamos a poner una función publica para que el botón pueda acceder

public void Pause (){
If(Time.timeScale == 1)
        {
            Time.timeScale = 0;
            velocidad = 0;
            is_pause = true;
        }
        else
        {
            Time.timeScale = 1;
            velocidad = 0.13f;
            is_pause = false;
        }
}

Acá podemos ver que la propiedad importante a usar es Time.timeScale, que lo que hace es modificar la escala del tiempo del juego, si la escala está en 0, el juego esta detenido, si esta en 0.25, el juego va a estar "en cámara lenta", una propiedad de la que se puede aprovechar.

Di un ejemplo de como sería si por ejemplo en mi juego hay un objeto a velocidad constante. Al poner pausa, como lo que hace mover al objeto no es la velocidad sino un cambio en el espacio, no es afectado por el tiempo, por eso tengo que "frenarlo" manualmente. Así también podemos poner unos flags que indiquen si el juego esta pausado o no.

Finalmente, queda asignarle la función al botón, para eso vamos a ir a la sección de "OnClick()" que esta en el inspector cuando seleccionamos un botón


Haciendo click en el más, le asigamos una función al botón, falta decirle que función, para eso vamos a:
  1. Agregar el Script al objeto
  2. Arrastrar el botón desde el inspector hasta esta propiedad "OnClick()" del botón
De ahí que podemos, desde una lista de elementos desplegables, elegir nuestro Script y luego, nuestra función. Aviso: El hecho de primero agregar el Script al botón puede ser innecesario en algunos casos. Yo lo hago por si quiero que varios botones tengan la misma función pero que, al accionarla, funcione solo para un botón y no para todos.

Para los que querrían que su personaje no se pueda desplazar, les recomiendo usar las Constraints del Rigidbody

Primero declaramos una variable publica (por si no lo hicimos antes) del RigidBody (en mi caso, 2D):

public Rigidbody2D rb;

y luego les asignamos el bloqueo de posición en el eje Y y Z.


rb.constraints = RigidbodyConstraints2D.FreezePositionX;
rb.constraints = RigidbodyConstraints2D.FreezePositionY;

para luego desbloquear esto, simplemente ponemos:

 rb.constraints = RigidbodyConstraints2D.none;

Y así queda creado un simple botón de pausa.

-L



----------------------------------------------------------

English
 
Buttons are fundamental for video-games, they are a tool that can't be absent in any game regardless the media on which the game is played. That is why today I'm creating a simple tutorial to teach how to create a pause button in Unity.

Although I think each game needs to be analyzed separately depending on its features, what we are mainly looking for is to create a state where every activity is stopped. Going into the details, we are going to stop time, as many functions depend on the time to work.

As there are some mechanics that don't depend on time (such as the displacement of an object which recieves an Input like a keyboard), this are going to be active whether the time is "on" or "off", that is why I mentioned earlier that there could be games that use special mechanics and that is why they need to be thought different.

First of all we need to create a GUI Button:



Now we create the Script (or we use one that we had before) on where are going to write a public function that the button can access.

public void Pause (){
If(Time.timeScale == 1)
        {
            Time.timeScale = 0;
            velocidad = 0;
            is_pause = true;
        }
        else
        {
            Time.timeScale = 1;
            velocidad = 0.13f;
            is_pause = false;
        }
}

Here we can see that the important property to use is Time.timeScale, that modifies the time scale of the game, if the scale is on 0, the game is stopped, if it is on 0.25, the game will be in "slow motion", a property which can be given different uses.

I also did an example of how it would be the case where I have an object that moves at constant speed. When I pause the game, the object will keep moving as the movement doesn't uses the time but the space, that is why I need to "stop" it manually. In the same way, we can create flags to indicate whether the game is paused or not.

Finally, we need to assign the function to the button. To do that we are going to go to the "OnClick()" section which is in the inspector when we select a botton.


Clicking on the plus we assign a function to the button, now we have to say which function, for that we:

  1. Add the Script to the object
  2. Grab and drag the button from the inspector to the "OnClick()" property of the button
From there we can, from a drop down list, select our Script and then, our function. Note: The step of adding the Script first to the object is not necessary in some cases. I use it in case I have several buttons using the same function and I want each one of them to work separately when I activate the function.

For those who would like their character not to move when it is on pause, I recommend to use Rigidbody's Constraints

First we declare a public variable (in case we didn't do it before) of the Rigidbody (in my case, 2D):

public Rigidbody2D rb;

Then we add the block to the X and Y axis:


rb.constraints = RigidbodyConstraints2D.FreezePositionX;
rb.constraints = RigidbodyConstraints2D.FreezePositionY;


Later, to unblock the axis we need to use:

 rb.constraints = RigidbodyConstraints2D.none;

And that is how we create a simple pause button

-L

No hay comentarios.:

Publicar un comentario