Category Archives: Videojuegos

Juegos creados por Drakon, Hunter. Misteriosa colaboración de diseño para crear singulares experiencias interactivas

Creación de personajes para videojuegos en 3DS Max P.1- Introducción

Bienvenidos a este nuevo tutorial sobre el genial 3DS Max! En esta ocasión, profundizaré en el manejo del programa para principiantes (no0bs!), mientras les enseño sobre diseño de personajes y modelaje orgánico del cuerpo humano!

Verán de todo, desde:
– El manejo de las herramientas del programa (si, esta vez les enseñaré a escoger las herramientas adecuadas y todo!);
– Técnicas de modelado considerando una adecuada topología (importante para animación!);
– Creación de ropa y cabello(también considerando topología);
– Aplicación de materiales (creandolos desde cero en su programa de edición gráfica preferido!);
– Riggeo del personaje (puede que cree el esqueleto desde cero, o use biped, dependerá si estoy de humor xD);
– Skinning (para que la piel y la ropa se muevan junto con el rig);
– Animación del personaje (cómo crear diferentes posturas animadas que pueden reproducirse luego en un videojuego);
– Importación del modelo completo a Unity (incluyendo mecanim!);
– Creación de un juego simple para mover el personaje con el control (para conocer los básicos, te recomiendo que vayas y veas el tutorial introductorio de Unity ;D

Unity 3D tutorial introductorio P. 1

).

Así mismo, ya había publicado el proceso de modelado de edificios con diseño de interiores. Pueden visitarlo si les apetece ;D

Proceso eficiente y simple para modelaje de edificios en 3dmax Parte 1

Proceso eficiente y simple para modelaje de edificios en 3dmax Parte 2

Al final, aunque no enseñaré cómo, tendré un mini juego perteneciente a mi serie original Freedom Wills, donde podrán jugar el intenso combate del capítulo 3, si se perdieron dicha serie, no olviden visitarla aqui!

¡Novela Capítulo 0!…

Capitulo 0 p. 1


¡Novela Capítulo 1!…

Capitulo 1 p. 1


¡Novela Capítulo 2!…

Capitulo 3 p. 1

¡Cómic Capítulo 1!…

Freedom Wills cómic, Aventura 1- viaje 1

El día de hoy, veremos una introducción a 3DS Max, cómo crear menues quads y dónde ubicar cada herramienta que se ocupará en capítulos posteriores y comenzaremos a planificar el modelo del cuerpo de nuestro personaje!

¡Comencemos!

Para comenzar, probablemente sea conveniente presentar el programa, en caso de que seas súper noob digo, principiante y de verdad no sepas nada de en qué te estás metiendo!

No temas, yo estoy aquí para ayudarte =D. 3DS Max de Autodesk es un programa de modelado 3d virtual (osea, no con plastilina y eso, si no, en la computadora xD), que comúnmente usan los artistas 3D para crear todo tipo de objetos de la realidad en un entorno simulado para usar, bueno, en otros entornos simulados.

Qué tipo de entornos simulados son esos, podrías preguntar. Bueno, simple, Unity es uno (otro monstruo enteramente independiente que puedes consultar en mis tutoriales introductorios!). Donde necesites usar entornos, objetos, creaturas, personas, todos modelados en 3D, para eso te servirá lo que hagas en 3DS Max.

En el caso de un diseñador industrial, puede usarlos para crear escenas con fotomontaje donde se superponen objetos 3 con entornos 2d, por ejemplo. Los arquitectos lo ocuparían para hacer un modelado de entorno completo donde ubicar sus edificios modelados en 3D también. Un diseñador de videojuegos lo pasaría al engine que maneje (como Unity) y lo usaría para su videojuego.
Si eres animador 3D en el mismo 3DS Max puedes animarlo e incluirlo en tu filme cgi.

Un ingeniero podría querer hacer simulaciones 3D con objetos para ver cómo interactuarían en la vida real.
Hay artistas de cómics (algo flojitos) que usan sus modelos para crear las bases sobre las cuales trazarán sus personajes en la viñeta, o directamente crean la viñeta con ellos.

Hay muchos usos específicos para este tipo de objetos, pero debes tener la idea clara de en qué lo usarás. Una ama de casa, por ejemplo, no lo puede usar en la sopa (xD), pero tal vez le interese modelar por diversión, relajarse o expresar su creatividad.
Mientras tengas creatividad e iniciativa, te sirve para todo!

Un aviso previo, para manejar este tipo de programas de modelaje 3D no ocupas saber ningún lenguaje de programación, algunos tienen funciones de programación, pero más que nada se usan para simulaciones o crear videojuegos dentro del mismo programa.
Esto por ahora no interesa, así que no temas.

Enlarge

3ds max
Este es un modelo simple de edificio que por dentro y por fuera se ve nice, hecho en mi previo tutorial de 3DS Max, chécatelo!

3DS Max

Lo que sí te recomiendo que aprendas un poco es sobre dibujo técnico y geometría descriptiva. Desempolva tus conocimientos sobre figuras geométricas, poliedros y polígonos, te ayudarán mucho.

Sobre dibujo técnico noes obligatorio que sepas hacer un plano técnico, pero te ayudará mucho saber sobre mediciones, escalas y proporciones.

Para comenzar, abre el programa empleando el ícono en tu escritorio, que aparecerá ahí sólo si ya instalaste el programa en tu computadora (no te diré como hacer eso, lo dejo a tu criterio si usar medios legales o dudosos xD).

Tendrás algo como esta pantalla, mi versión es 3DS Max 2017, si consigues esa, perfecto, si no, no te preocupes. Las herramientas y principios son los mismos, si acaso cambiarán las ubicaciones y demás.

A mí me gusta comenzar a usar un programa siempre enfocada en productividad y eficiencia, la mejor forma de lograrlo es conociendo los secretos del programa y sus shortcut keys.

En el caso de 3DS Max 2017, la mejor forma de sacarle provecho a los shortcuts es por medio de los menúes quad. Comienza por abrir la ventana de Customize User Interface y escoge la pestaña Quads.

Puedes dejar todo lo demás exactamente igual y predeterminado, lo importante aquí es configurar los quads.
Qué es un menú quad? Es una ventana personalizable con una serie de herramientas que tu desees y que aparecerá al teclear una combinación de teclas que tú establezcas.

Aquí puedes ver el ejemplo del quad Modelling que yo creé, que contiene una serie de menúes desplegables más que agrupan una serie de herramientas más que vienen congregadas así predeterminadamente.
Debajo de la herramienta Relax puedes ver una serie de opciones más en un color opaco (y no blanco, como Relax), esto es porque esas opciones son contextuales. Cuando puedas usarlas el programa las activará para ti.

No te preocupes mucho si no sabes para qué son ahora, te las iré explicando a grandes rasgos (las más principales) conforme sean necesarias.
Por ahora, volvamos a la ventana Customize User Interface y dale click en New…

Dale un nombre adecuado a tu menú Quad en el campo rellenable New Quad Set.

Cuando le des click en Ok, puedes revisar en el menú desplegable sobre la opción New… Tu recién creado menú quad estará enlistado ahí!

Pero eso no es todo, pues tu menú ahora está vacío! Y no tienes aún asignado el acceso directo hotkey para activarlo! Resolvamos eso!
En el campo rellenable Quad Shortcut escribe cualquier código que gustes, una combinación de ctrl, shift, alt y cualquier otra tecla funciona bien, mínimo 3, pues 3DS Max ya tiene muchos shortcuts preconfigurados con combinaciones más simples (como ctrl + c, por ejemplo), que son más fáciles de recordar. Si las sustituyes, luego le restarías poder a la preconfiguración de 3DS Max.

Por eso, te recomiendo que inventes una combinación más compleja, como puedes ver en mis menúes quad personalizados Custom Transform Simple, Custom Select Contextual y Custom Modelling, todos con su código único como shift + ctrl + a, por ejemplo.

Para asignar el código shortcut deseado, dale click en el campo rellenable Quad Shortcut, luego oprime las teclas deseadas, manteniéndolas presionadas para que sigan siendo consideradas en el código. Hasta que teclees una tecla de letra (Y, por ejemplo), el código se quedará en el espacio editable (porque no puedes sólo asignar teclas de acción como ctrl o shift, son muy genéricas!).

Una vez que hayas establecido un código, oprime Assign (que será visible sólo si el espacio rellenable quad shortcut no está vacío). Cuando un código no sea único, es decir, esté repetido, te aparecerá un mensaje de advertencia. Si deseas sustituir un código predeterminado por 3DS Max, dale click a sí, si no, dale click a no e introduce otro código más especial!

Finalmente, una buena práctica para no olvidar tus códigos (y que yo hago en mis menúes quad), es poner el código establecido como parte del nombre! Así, cada vez que abras el programa, puedes consultar qué código tenía dicho menú quad y poder accesar a él después.
Yo he encontrado que mi 3DS Max tiene un raro bug donde los shortcuts para mis menúes quad siempre se desconfiguran al reiniciar el programa. Así que tengo que volver a asignarlos cada vez, poner el código en el nombre me ayuda a saber qué funcionaba previamente y seguir respetándolo (;D).

Ahora, como eres principiante (noob xD) y no sabes qué onda con las herramientas, te ahorraré la molestia de tener que buscar qué herramientas son mejores y todo eso y te pasaré mi configuración preferida de quads.
Puedes llamarle igual y ponerle los mismos códigos de acceso o no, tú decides.

Lo importante es que cheques el dato de las opciones que en ellos agrupé. Para empezar, las “herramientas solas” las puedes buscar en la lista de la izquierda. Si tecleas la letra inicial del nombre te llevará automáticamente hacia todas las herramientas ahí enlistadas bajo esa letra. En mi menú quad una herramienta individual aparece como un nombre con una linea horizontal simple que se une a otra línea vertical que se conecta al resto de las herramientas escogidas.

Una vez que encuentres la herramienta adecuada, dale click y sin soltarlo, arrastra el nombre de la herramienta a tu listado del menú quad (checa el área 3).
Para facilitar la lectura y selección de herramientas, añade líneas punteadas separadoras que también puedes arrastrar y soltar en el espacio que desees.

Muchas veces 3DS Max ya tiene menúes preconfigurados llenos de muchas herramientas útiles que puedes aprovechar y te ahorra el trabajo de buscar herramientas individuales o crear esos menúes tú mism@ (si se puede, en la pestaña Menús).
Puedes buscar esos menúes de la misma manera que las herramientas solas y arrastrarlos y soltarlos en el lugar que tú desees!

Una vez que rellenes con las herramientas que gustas en el menú quad de tu elección, puedes escoger en qué posición del menú quad (dividido en 4, he ahí su nombre), aparecerá tu menú creado (checa opción 1).
Yo escogí para todos la esquina inferior derecha, pues me parece más natural para mí ir hacia esa dirección para buscar herramientas, pero tú establece lo que gustes y experimenta cuál se te ajusta mejor.

Además, puedes asignarle una etiqueta Label (checa el área rellenable 2), para que tu menú quad tenga un nombre cada vez que se despliegue y así sepas si es el indicado o no, y porque así se ve más pro!

Una vez que termines de rellenar un menú quad, te sugiero que oprimas la opción Save… y guardes tu menú donde mejor te parezca, ponle un nombre relacionado. Esto te facilitará llevar tus menúes quad contigo y usarlos en cualquier otra computadora aunque no sea la tuya original (;D).

Ahora ya estás list@ para trabajar eficientemente en 3DS Max! Usar tus menúes quad te ahorrará tiempo en buscar las herramientas en todos lados, eso siempre te quita tiempo y es engorroso aprenderse dónde está cada cosa. De igual manera puedes aprenderlo, pero toma en cuenta que sus posiciones varían de versión a versión.
Por otro lado, no estoy segura qué versiones de 3DS Max soportan menúes quad, así que yo igual te estaré instruyendo cuando sea necesario sobre dónde encontrar una herramienta dada.

Ahora que estamos de frente al workspace de 3DS Max, podrías estar intimidad@ por la cantidad de opciones y la extraña división del espacio que hay. Qué son todas esas cosas!? No te preocupes, por el momento no necesitas ocuparte de la mayoría.

Pero si es importante que te familiarices con tu espacio de trabajo.
La división en 4 rectángulos es lo que se llama workspace, funciona como típicamente se orientan los dibujos en un plano de dibujo técnico, en la esquina superior izquierda tienes la vista superior (Top), en la que está a su derecha está la vista frontal (Front), y debajo de Top tienes la vista izquierda (Left). El último rectángulo nos mostrará el objeto en perspectiva, es decir, la proyección tridimensional real del modelo, que te permitirá explorarlo con libertad para que sepas cómo es.

Aquí puedes apreciar cómo se visualizará un objeto cualquiera a través del workspace de 3DS Max, con la orientación como debería ser en dibujo técnico.

Ok, está algo invertida en relación a como deben orientarse las vistas para un plano técnico, al menos en el sistema triédrico americano (el europeo está invertido, pero tampoco es similar a este!).

Pero eso no importa, porque tú no harás un plano técnico aquí (para eso, ocuparías exportar el modelo a otro programa! pero si no te interesa eso, a mí tampoco xD); lo importante es que sepas cuáles son las vistas del objeto que estarás visualizando ahí, y construyas tus modelos en base a ello.

Para guiarte mejor, básate en esta ilustración simple que hice de una silla fea y sus proyecciones en las 6 caras de un cubo.

Básicamente, el dibujo técnico toma su orientación de este concepto.
Si cada cara del cubo fuera de vidrio y vieras a través de una de ellas a la silla, lo que verías sería algo similar a lo que está dibujado en la siguiente ilustración. (imaginémonos que tus ojos no ven con perspectiva el objeto, si no, ortogonalmente, osea, todas sis líneas salen paralelas hacia el horizonte y en consecuencia, el objeto es plano!).

Lo que ves aquí son las diferentes caras del objeto (nombradas en verde). 3DS Max usa este mismo concepto para orientarte en base al objeto y permitirte modificarlo a tu antojo con facilidad.
Puedes ver que algunas caras parecen repetirse, la frontal es similar a la posterior (esta tiene líneas punteadas), la izquierda es similar a la derecha (o más bien, idénticas!) y la superior es similar (esta también tiene líneas punteadas!) a la inferior.

Si te fijaste bien en esas que no tienen líneas punteadas, nos dan una idea más cercana de la realidad, pues la silla no tiene patas o asiento invisible. En dibujo técnico, las líneas punteadas se usan en un dibujo para indicar que hay otro objeto detrás de lo que se ve, se llaman líneas ocultas y dan una pista de que hay algo más allá, pero como tienes otro objeto por delante, no se ve.

Para crear un plano técnico, por lo común, se toman las vistas que te dan más información, un mínimo de 2 caras (si es un objeto con simetría radial o algo similar) y un máximo de todas las 6 caras. Pero lo más usado son 3, la frontal, superior y alguna lateral.
Siempre nos dijeron en diseño que la cara frontal es la que te da más información del objeto, así que en base a este concepto, la silla del dibujo sería así…

Cuál cara te da más la idea de que es una silla? pues obvio, la que te permite ver el perfil completo de la silla, desde el respaldo hasta el asiento y los descansabrazos.

Pero en 3DS Max no es tan fácil como redibujar el objeto, es más fácil, de hecho, se puede rotar en el mismo espacio virtual del workspace, la división sigue igual, su organización también, pero la silla se ha girado para encarar la dirección deseada (eso lo veremos más adelante!).

Puedes ver que me aseguré que la vista derecha no tuviera líneas ocultas, pues de esa forma, nos da más información.
Sin embargo, la superior sigue siendo igual, en el caso del dibujo, tiene líneas ocultas, pero que eso no te preocupe, esa información te la dan mejor la frontal y la lateral!

Las vistas triédricas estándar son la frontal, la derecha y la superior. Cualquiera de las otras 3 servirán sólo para mostrar un aspecto único del objeto que no se alcance a apreciar con las 3 estándar. Pero ello sólo será aplicable en el caso de que estés haciendo un dibujo técnico.
Si sólo estás modelando un objeto en 3d virtual, no te preocupes por ello.

Además, ubicar correctamente tus objetos en el espacio te permitirá que cuando los exportes a otros programas (como Unity, por ejemplo), estén orientados como se debe y sea más fácil la tarea de ubicarlos en el espacio.
Es una buena práctica que debes adoptar ;D.

Por hoy, es todo lo que veremos de 3DS Max, pues ya ocupé mucho espacio hablando de ello! Hay que enfocarnos ahora en la creación de nuestro personaje que modelaremos!

Tú debes decidir qué personaje vas a modelar, diséñalo por tí mism@. Yo, obviamente, modelaré a la protagonista de mi historia Freedom Wills, Janie Ruy (lee la historia si no sabes de quien hablo xD).
A mí siempre me gusta dibujar el personaje de cuerpo completo en perspectiva a 3/4, me da una mejor idea de su personalidad (postura y expresión facial), sus dimensiones y complexión física y sus gustos personales (ropa y accesorios).
Además, es importante que definas de antemano los colores que manejarás con el personaje, así será más fácil texturizar el modelo más adelante.

Lo primero que debes hacer para tu personaje, es un estudio de sus rasgos distintivos, cabello, ropa, complexión corporal, rostro y accesorios varios.
No te daré un tutorial de diseño de personaje, no aquí, pero si quieres uno, pídelo y con gusto (;D).

Dibuja cada característica en todas las vistas que sean necesarias para que comprendas cómo se estructura el objeto y tengas en claro qué

Una vez que has definido y estudiado adecuadamente tu personaje, procede a realizar un tipo de dibujo llamado posición en T, ésta postura ayuda a que modeles el personaje de manera tal que cuando riggees y animes el modelo, no pierdan proporción sus extremidades.

Se dice que la postura en T es más apta para personajes caricaturizados y la posición en A es más apta para personajes realistas.

En realidad, puedes usar lo que te parezca más cómodo, pues el estilo de animación será definido por el estilo artístico que uses, y la calidad de la misma por la topología que le imprimas al modelo.

Pero qué es topología, preguntarás.
Bueno, imagínate que tu personaje es una esfera, y que simulará una pelota de volleyball o algo similar, debe tener divisiones para ello, una simple esfera no podría parecer una pelota de volleyball, verdad?

Para que sea una pelota de volleyball, ocupas que tenga esas bandas extrañas que no comprendo y que la rodean por donde sea. También imagínate que esta es una pelota de volleyball (no tengo internet para comprobarlo y no soy experta, asi que esto deberá bastar xD).

Pues bien, esas l+ineas básicas que cruzan a lo largo, profundo y ancho la pelota son las líneas de la topología. No es lo mismo tener algo limpio y bonito que te ayude a crear un modelo estético y bien proporcionado y algo súper enrollado y absurdo que entorpezca el resultado y encima haga que al animar la pelota se deforme toda.

Una adecuada topología siempre obedece al flujo geométrico de la figura que estás creando y te ayuda a que la textura, el riggeo y la animación salgan con más fluidez, limpieza y estética visual.

Normalmente, debería enseñarte cómo se dividirá el personaje en sus líneas de topología, pero lo dejaremos para el próximo capítulo.

Unity 3D introductory tutorial P. 2.2- Moving the character

Welcome back! Again we have no downloadable assets because everything you need you can get it somewhere else, like in the internet or something like that. There are no new art assets and the modified gameobjects and created script are better done by yourself following the tutorial.
But there is a playable Live Demo of this tutorial! Go take a look if you want to!

First of all, last time I didn’t mentioned it, but this is a pretty crucial point to take into account, also, there is interesting theory you should know about. We already have collision detection on our character (CapsuleCollider and CharacterController), but do you know what that is or how does it work?
You have to determine where and how the character is going to interact with the world through collision so the metrics can work adequately. Collision is determined from a primary point on the character model. There are generally three locations on a character from which the player can interact with the world:

The head: This point as the main collision point can cause problems, specially when determining ground collision (isGrounded character controller function on Unity). The character can appear to not be rooted to the ground, giving the appearance of slightly floating.
The feet: this may seems the logical location for collision detection, but it can cause issues if it is used to determine where a power-up is collected (for example, if it is mid-air, the character will have to jump to collect it).
The torso: according to Level Up, this is the best place to determine the character’s collision with the world. It provides enough coverage for both halves of the body and feels ‘right’ when the player runs or jumps through an item for collection.
But let me tell you a secret, this won´t matter as much in Unity! Yeah, you still have to consider all those points of collision, an all body collision may be needed even. Especially if you are using a completely rigged 3d model: it can extend arms and touch objects with its hands (or even forearms, upper arms, fingertips!), it can extend legs and kicks some stuff, it can even extend its head and touch the ceiling. Whatever can be an important collision point for gameplay!
You may not know about this, especially if you are just beginning with game design and are young, but before, people only had at its disposition collision boxes, circles and sometimes capsules, and they had to be placed in a way it covered the majority of the character’s sprite so everything touched by the box could be interactable and the player could see it as the character touching something and not some mystical invisible box.
Well, those days are over, because in unity, you can have as many mini colliders as you may want! Each fingertip with its own collision box (even cylinder, or even better, mesh collider with just the shape of that fingertip!). Each leg, each arm, whatever you want can have its own collider, according to its particular form, and move alongside with it (through child-parent relationships). Whatever can have its own collision detectors so you can have micro interactions alongside your model.
Think of a giant troll touching everything in its path! Stepping over townsfolks, grabbing houses, eating a little sheep, whatever you can dream of can be done! Of course, all those micro collisions will consume its share on resources, but you can worry about that when you get to it.
For now, we have already put our collision detection on this character of ours, remember CharacterController, right? Since this is a very simple 2D game, we won’t indulge in such things as micro collisions on fingertips, we just need something that will cover the entirety of the sprite, something simple, since a 2D game can do without those complex things.
However, Unity manages simple collision detectors in the form of the various Colliders it has available. One of these is through the CharacterController itself, also, the RigidBody has its own kind. But the most easy to learn are the ones below and including then BoxCollider, because their detection is more easily controlled and programmed by a beginner.

Remember we had a CapsuleCollider on our character? Well, let’s change it a bit, because right now we won´t indulge too much on that aspect (first we need to configure the items and props it will collide with, and that’s for another tutorial! Wait for it).
First of all, mark the checkbox on your MeshRenderer, so that you can see the CapsuleDrawn By the collider, and next up click on the little cog wheel besides the name and select Remove Component. We won´t need that pesky capsule anymore! Do the same with the CapsuleCollider and the Capsule (Mesh Filter). We don’t need no more of these things!

Make the CharacterController as slim as you can modifying the Radius. Remember that BoxCollider from before? Select and add it to you Character Control gameobject

We need the BoxCollider it will cover more ground that the capsule (because of its shape). Next up, change the BoxCollider to trigger by marking the checkbox on isTrigger (this will allows the collider to be penetrable by objects, while at the same time, detecting collision). And play with the size fields until you have something that covers around the middle body and head of our character, while at the same time, getting out of the CharacterController zone.
When you have both CharacterController and whatever other Collider in the same gameobject at the same time, the first tend to block the latter, making it unable to detect collision. Besides, we don´t really need the CharacterController to cover up all the character sprite, that would make it difficult for it to navigate in narrow spaces. You know how in real life you can always compress your arms to your body so that they won´t bother you in these situations? Well, this is the equivalent of it.
Also, it’s good to have the collider a little outside the body, because that way the collision detection is more natural; not so much that it appears the character has psychic powers! But enough so that you don’t really need to stand directly up and cover all the things you need to collide with.

For now, we are fine in the collisions department, our character is ready to begin colliding with things! But our focus right now is only on movement, so let’s get going with that!

Remember last chapter how Gun McShooter was sleeping soundly and dreaming of black waves, then all hell broke loose and the train with the money exploded? Whew, do you!? I don’t! Tell me more! Hahaha, because I remember something like Gun being unable to turn around and just walking around from side to side and such, wasn’t it fun?
Kidding! Don’t kill me (yet!) Now, I’m going to show you, not only how to make him move differently, but also, how to move faster, jump higher and even fall again to the ground! Put your gun belt and prepare yourself for some more coding action!
Well, now that we are going to add some physics controls to our hero which in turn, will serve as the metrics controls too! We need to define some basic things that will improve or difficult our gameplay, that´s right, the character will affect directly into the players experience of the game!
You have to know and always remember that all gameplay flows from the main playable character (it can be a person, vehicle, animal, an abstract object, even geometrical ones like tetris! Whatever you move, that is the main character!). You have to think about the player’s relationship to the world:
Its height, reach, means of transportation, longitude and volume. Whatever you can think of that constitute the proportions for metrics.
While moving, the character must be able or unable to reach some gameplay objects (whatever the character can interact to, is a gameplay object).
There are distances for climbing (you have to jump? You can climb directly from the ground? You need some force to help you climb?); walking (how wide must a path be for the character to walk through it? How steep the ground until the character falls back down sliding? How far can you go until the character tires itself by walking or running?); jumping (what can you reach in a single jump? Can you jump twice to reach farther? Can you extend your jump by running? Which direction can you run, vertical, horizontal, diagonal?); crouch (do you have to crouch to get into small spaces? Can you reach other superficies and objects by crouching?).
And whatever else you may think. Always think first on the action and immediately after, the conditions this action can affect gameplay.
Just remember, walking alone is not gameplay, but the variations of conditions in which you can walk and the alternatives you can have to walking that will allow you to reach farther and better some places in the playable world!

Metrics are very important to players, because they use them to gauge movement and reaching distances just “by eye”, even if they are conscious of it or not, they will catch up to it sooner or later and try to exploit it to their advantage.
There are few things more satisfactory than knowing how you can mess around with metrics and controls to reach hidden places and secrets. I remember always trying everything in my reach to play through a zone faster, or breaking some limit, or achieving a trial with less effort. You can feel a pro just by getting used to these metrics and controls, or like a dummy for not knowing what to do with your character.
It all depends on the design, so think carefully about these aspects and play with them consistently so the player can enjoy the game and have some good time trying to best himself in whatever trial you put him through!
In order to correctly asses metrics, consider the basic height of the character, the speed the character travels, the height it can reach, how much it can fit in a place, so on and so forth, it all depends on the context of your game.
I can suggest you to take your character as the measure unit, like ‘5 character units (CU) wide’ or something like that. Also, when designing you environment, props and enemies, make sure to use your character as the base unit to scale them up. Your enemies can be like ’10 CU of height and 5 CU width’, and some pathway like ‘3 CU wide’. Always keep this in mind and the world around the player will feel right.
If you don’t believe me about the importance of metrics, I will suggest you to take a look at that creepy Lara Croft videogame (I think it inspired the movie, but I´m not sure), where she killed a bunch of innocent tigers in the Himalayas. In that very same game, her house was this gargantuan mansion where she could take a bath in the water basin or cook herself in the oven!
It was bizarre, like some kind of Gulliver with guns and polygonal boobs xD. But I can understand why they did that, from a designer point of view, maybe their collision detection weren’t so perfect as what we have today, and in order for her to fit in her house, it should be like 10 CU wide in scale. Weird!
Fortunately, Unity is far better at collision detection, so we can measure correctly and make pretty games at the same time!
In this case, we will leave these options free for the game designer to play around with…
-Height: the height of the player character.
-Width of passage: usually wider than the player character.
-Walking speed: how far the player travels per second or unit of time.
-Running speed: how far the player travels per second or unit of time but faster.
-Jump distance: usually farther than a walk, but not as far as a run; can also be based on the player’s width (like 5 CU across or so).
-Jump height: based on the character height, a jump can be half the height of the character, while a double jump can be twice as tall the character and so on.
-Melee attack distance: usually not much farther than the length of the player´s arm and weapon.
-Projectile distance: this can be as short as the player´s reach or width to as far as the player can see.
An example of how to apply this, can be seen in this image taken from Level Up…

The cliff ledge shown in the above graphic is obviously completely unobtainable with a normal jump/ double jump distance. So the player will know that they won´t ever be able to reach this height and will look for another way to get to their destination, a well thought out obstacle!

For this very same reason, we are going to stablish in our nifty code some variables that will allow us to modify the properties of physics and scale it during play test in real time! (when we have the code that will make it work, you can click play, then modify the variable values to make them affect the movement in real time, so you can know which values are right and so on).
What we will need to add are the following variables…

These variables have names that are self-explanatory, also, I added some default values in case you forget to set them in the Inspector, they are public so that you can do so.
Now, for what are they? We are going to use them to construct our rotation control for the character, that way it can turn around and face different directions! But they do need more friends to make it so! Just add these other variables, this time, inside the Movement() function, just above whatever other code you have there, because variables are better declared at the top of everything…

They are called somewhat close to what they do, but I can’t really explain what they do without showing you the instructions where they are used! So let´s add some more code to this!

Wow, we added some new instruction we haven’t seen before! You learn new things each time you open one of my tutorials (XD). Well, that little thingie if (CharaControl.isGrounded) is the application of a helpful conditional instruction called ‘if’, have you heard that phrases “if you eat vegetables, then you grow taller!”? Well, this is like the same thing, only with a twist! If you do whatever condition is written inside the (), like CharaControl.isGrounded, then whatever you encased in the {} below the if condition will be executed!
But what about !CharaControl.isGrounded? Do you remember that variable that kept the CharacterController of our playable character? Well, since it refer to a class, and classes tend to have functions, isGrounded is a Boolean (yes or ! not values) function. When it doesn’t have the !, it should check for a positive value (the character should be grounded!), but if it has it (! Not symbol before the variable name), then it should get a negative value (it is floating and not grounded at all!)
Also, it checks whether your CharacterController is touching the ground or not, that’s why it is important to have a ground and make sure the CharacterController is exactly the same height your character sprite is.
This basically means that, whenever your character is not touching the ground, it can move with velocity being equals to move * moveSpeed (since we don’t have gravity activated yet, so we won’t be able to make sure it is always touching the ground while not jumping!). Remember what was velocity in your physics classes? Well, me neither, it was something like distance / time or something like that (xD I’m not physician either, but I make do with what I have!). Move is supposed to be the distance (like when you triangulates the walked distance in a map? With the latitude, longitude and height or something like that, I’m not geographer either!). MoveSpeed should then be the time, but whatever, it works xD.
Now erase the velocity = move; code you put the last tutorial and click test play! How was that? Did it moved more quickly? Try changing the MoveSpeed value and see what happens! That’s fun! You can move at whatever speed you want now, just changing this thing! Yeah!
But what about the other variables? Well, each one has its use specially for changing the problem with the facing of character while it moves. Let’s see about that. Add this code just above the CharaControl.Move (velocity * Time.deltaTime); and play close attention to the localization of velocity = transform.TransformDirection (velocity); an instruction we already have set…

We have assigned the value of velocity.z (in its z axis) to ForwardAmount, then did some kind of mathematical operation (class Mathf, function Atan2, I really don’t understand what it does, but you can check on the Reference Manual and see if you have better look xD), that plays with the axis x and z of velocity.
Another mathematical function (Lerp) that plays with all the other variables we assigned first (StationaryTurnSpeed, MovingTurnSpeed, ForwardAmount), because reasons (I really don’t know, I just followed an example on rotating the transform of an object and go on with it xD). But I can say Atan2 gets you the angle distance between point a (velocity.x) and point b (velocity.z), so that you can get how much distance is needed to cover that up when rotating your gameobject. Lerp gets some kind of value for setting the speed, so the rotation can be gradual and not sudden and choppy!
The interesting bit is the transform.Rotate, transform refers to the Transform Component of the gameobject the actual script is attached to, is like a predetermined variable of type Transform you can use to avoid assigning it yourself, Unity detects it automatically. The rotate function refers to the Rotation fields on the same Transform Component, it passes through the values you set as angle an makes the rotation according to that values.
Now you are ready to try it out! When you advances forward, the character goes that direction, but whenever you press any other direction, left, right or down, the sprite rotates, taking the camera with it and changing its facing direction! This can work, if you want a tank like control on your character.
However, if you want something more natural and useful for a third person shooter game, the character needs to be able to go up, down, rotate when going to left or right, and also, maybe being able to go left and right without rotating.
There are many complicated ways to do this, but I have one simple solution using only the code we already have plus some little aditions. Do you want to see that? Then add this code to what you already have…

As you can see, we still have ForwardAmount = velocity.z; and TurnAmount = Mathf.Atan2(velocity.x, velocity.z); assignments, only enclosed within the conditional if (Input.GetAxis (“Vertical”) == 0) {}, here we are checking whenever the player is not going up or down (Vertical axis is not -1 or 1), the instructions on this code will execute. The ==0 is the comparison we are making.
When we need to compare a numerical value (Input.GetAxis retrieves a float value, which means, numerical values with decimals) and see if it does have a given value (in this case, by pressin Vertical axis you can get 1 or -1 value, positive going up or negative going down), we need to add < (minor than), > (major than), == (equals to), <= (minor or equals to), >= (major or equals to) or != (different to) signs. If you want to learn more about this, look in C# documentation about conditional instructions and comparison signs so you can get a clearer idea about what they are all about.
In this case, when the character is just standing there, we can rotate it by pressing left or right. An extra ability is that when you are going up or down you can go sideways in that direction by pressing both Horizontal and Vertical axis. That’s great, isn’t it?
The “else” part is the alternative behaviors to what happens when the condition in “if” is not happening in the game. You can have as many “else” as you want (many alternative behaviors) by writing “if else” instead. This is like saying “IF you do have eggs for breakfast, you can bake them, IF ELSE you don’t have them, eat ham, or ELSE if you have neither of them, take a bowl of cereal”. Now it have more sense, isn’t it?
Go ahead and test the game! You can see how when you press up, the character goes normally up front, when you press down it backs down facing the same direction (useful if you are shooting enemies while at the same time, trying to get away from them!).
Also, when you only press left or right, the character rotates and changes direction of facing. This is going to be useful to correctly navigate maps and such, because now you can see where you are going and not just going sideways while always facing the same boring direction forever!
And the extra ability happens when you press a combination of Vertical and Horizontal axis, try it out! Now you can go sideways while advancing or retreating, perfect for dodging enemies, hiding behind obstacles and looking for an opening to begin your attack!
Try changing the variable values and see what happens, experiment with them until you got the correct combination. If you do this during gameplay, maybe you may have noticed the changes won’t stick when you stop the play test! Oh no! How are you supposed to set the right values now? Well, I will show you a little nifty trick.
Remember that little cog wheel beside the Component name? Change values and click on it while play testing and choose Copy Component, then stop play testing and click on the same cog wheel, choose Paste Component Values and you are good to go now! You can do this with whatever component you may want to change, but remember doing it with just one at the time, because it only works like that.

Now we have learned the basics of coding with Unity and C#, established controls, collisions and make our little cutie character move according to our will, muahahaha!! What’s left to do in this tutorial? Nothing, goodbye, I have to sleep…zzzzzzzzzzzz

Hahahha, just kidding! We haven’t added the acceleration and jump stuff (we already have the controls, don’t we?) and I promised you to introduce the music controls too! So let’s go on with some final details!!

Let’s begin with the dash movement, do you know what we need first? I will give you some minutes to figure it yourself. Remember we always need to manage variables in order to get values and play with them!
Do you know the answer now? That’s right! Variables! (I fell like Dora the Deported Explorer xD).
Let’s add the variables… You can see I added a little title comment, I like to tag my stuff like that so I can classify it better and know what everything does, try it out yourself ;D.

Then add and modify the if (!CharaControl.isGrounded) part under Movement() function, that is where we control the main movements of our characters, so everything that modifies it should affect here!
Erase the “!” from where it is and add an “else” condition, where you tell what to do whether the CharacterController is grounded or not. If it is floating (while jumping, for example) it can’t use the dashSpeed to increase the velocity, because you can’t dash without touching the ground (unless you have motors and are an airplane or something!).
If it’s touching the ground, dashSpeed is going to be added to MoveSpeed, increasing the velocity! (that’s why it’s important to have a base MoveSpeed not so much quickly as the dashing one).

Now you have to make a function that will control the dash increment, you already had assigned the button for it, do you remember it? The if (Input.GetKey (acelerar)) part will check if Acelerar key is pressed (GetKey checks on the keyboard keys, because they are not axis like with GetAxis).
If the key is pressed, dashSpeed will be assigned the MoveSpeed value multiplied by dash amount (it should be like a percentage of .2% or something like that, a low value but higher than 0 so it can have an increment!).
The “else” part will return dashSpeed assigned by 0, which means, if the acelerar key is not pressed, there will be no acceleration.

The final step is to call the function from the Update() function so that it can constantly affect the movements of our character.

And that’s all! You can even assign the acelerar key from the Start() function so it won’t be empty if you forget to assign it like so… You put a conditional to check if accelerar is equals to KeyCode.None (which means, it has an empty value), if it is, then the default value will be assigned, if not, then it is left as you put it. Now you can play test it!

You may have noticed the character is not accelerating at all when you pressed the designated key, right? Also, when you go out of the terrain limits, the character won’t fall over to a certain death! Well, that’s because the character doesn’t have any gravity to speak of! We need to set it up first! Add the following variables!

They will control how much force the character jump has, and how much pull the gravity that influences it will have.
Let’s go ahead and put default values to the jump key input…

Do you have any idea where the jump value would affect out character movement? Think about it, I will wait for you….
Are you ready? Remember the dashSpeed influencing over velocity? Do you think jump values affect the same? Woah, you are right! (I know you were thinking about it, I’m psychic like that ;D). But it won’t affect the entirety of it, like dash did, because we only ever jump up, but it can combine with other movements to, because it affects the character displacement in the up/ down axis, what’s that axis?
Well, remember this instruction… move = new Vector3 (directionX, 0, directionZ); and then this other velocity = move * (MoveSpeed + dashSpeed); we assigned the displacement in X and Z axis to move, which in turn was assigned to velocity, but we left the Y displacement like 0! Not anymore! Add this code between the others you already have (be careful not to write them down again! Be observant and learn to identify what you have and remember it even if for a few hours =P).

That’s right, velocity.y (the axis Y in velocity that wasn’t assigned by move!) will be assigned by directionY! That’s all, you made it! No, wait! What did you do? Where are the variables we have just declared for this? Aah, do you really thought they were going to be used directly like that?
Nope, direction will keep the value they return, but we need to make a function for it…

That’s it, her you can see we assigned jumpSpeed (and dashSpeed) to direction, but only if the character is already on the ground (if it’s not, it can’t jump again, can it? Unless you want double jump, but this is no magical cowboy, sorry xD).
If you have already jumped, but still want to press saltar key, then you are out of luck, because here we have assigned some value to gravitySpeed (it will increase according to deltaTime), and multiplying it by gravity, both will be decreased from directionY.
Your character will only jump so far (to reach the designated value on jumpSpeed or that plus dashSpeed), then fall all over again. This is the part where you can assign the double jump, assigning jumpSpeed again to directionY.
And even if you don’t try to jump again, you are going to start falling. The good news is that you can still move sideways, so you can do horizontal jumps in whatever x or z direction you want to!
Now you have set up successfully dash and jump moves! Go and try them by yourself, remember the controls you assigned and have fun! Don’t forget to tweak your variable values so that the character behaves as it should ;D
There’s only one more thing to do, the music! Right now, we are just going to set up SFX, that will sound when you walk and also when you jump. Search for sfx that you like from whatever videogame you want and then pass them to your project asset folder SFX.

Now add an AudioSource Component to your CharacterControl gameobject. This will make your gameobject into an living (virtually) speaker! Leave the default values.
You can have a lot of applications of this component, like people walking around listening to loud music, tv speakers, stereo speakers, whatever, try it out when you want! Also, we will need it in order to set some SFX to our character, it will be recycled with every sfx it needs!

Just to be sure, add this extra code above your class definition, so that everytime you add this code, an AudioSource Component will be added! If you forget to do so, don’t worry! Taking this kind of precautions allows you reutilize the same script over and over without having to remember much about it.

Now it’s time to add our well known variables for the audio control! AudioSource needs to things to work correctly as a recyclable component. First, assignment of AudioClip type variables, which will contain the sfx clips you search for in the internet! I called mine stepSound (for walking) and JumpSound (when jumping). You can even ad one for dash and whatever else, once you learn how to set it up for something, you can set it up for anything!
The second things is AudioSource type variable, it should be private, because we are going to assign it internally (you can assign it publicly too, but let’s try this one so you learn how to do it yourself!).

So let’s begin with assigning AudoSource, when done internally by the script itself, it is called Initialization (or something along these lines). Basically we tell the script to assign a declared variable (AudioMove in this case) a given component this gameobject should have. If we know it has it, we shouldn’t have any problem (that’s why we make sure this script will always require for our gameobject to have it and add it itself!). But if you forgetfully forgets to add it up (or deactivates it through unmarking the checkbox!), the script will behave erratically and have bugs and make everything else explode!!

Be very observant of your codes and what they need, a well thought-out script is a happy script xD.
Now GetComponent is not a function, variable or conditional of any type, it is a method Unity has defined internally (its own API) in order to control these kind of things like getting external components and such. Whenever you use it, you should add the component name (class) between the ();
Once you are done, you have successfully initialized a component type variable, now we can freely use it!
We need to assign sound when the character does move and when it jumps. Do you remember where we control each one? That’s right, the functions! Go to Movement() and add this code where you see it chilling out…

The “if” conditional checks whether velocity in X and Z is different (!=) to 0 (which means, it is moving in some way! But at the same time, it checks if CharaControl is on the ground (if it’s not, you can’t really step, right? Your feet can’t make a sound over the air!).
But how are we checking various things simultaneously!? Well, play close attention to the && (and) and || (or) symbols, they are used to add or substract conditions to instructions like these.
If you have && then the instructions at both sides of the symbol will be considered (you should be moving up or down while on the ground). If one of these is not valid (you aren’t moving up or down on the z axis or you aren’t on the ground), then it returns false and the instruction in the code block won’t execute.
However, the || symbol checks if whatever instruction at both sides of the symbol is valid (you can be walking on the ground up or down or walking on the ground left or right). If one of these is, then the instructions in the code block (between the {}) will execute!
Also, to facilitate reading and make it clearer to the code what you are trying to do, don’t forget to group instructions around symbols inside (), that way you can easily know what it should accomplish and the code won’t get confused. You can see (velocity.x != 0 && CharaControl.isGrounded) and (velocity.z != 0 && CharaControl.isGrounded) are both encased on their own unique (), because they both have inside a && symbol, but both are grouped around a || under another pair of ().
Also, the if (!audioMove.isPlaying) {} checks whether the AudioSource type variable audioMove is currently playing some sound, if it isn’t (!), then it will execute the instructions insided the code block: audioMove.clip function will be passed the sound that stepSound keeps, and audioMove.Play() will be executed, playing the designated sound. And that’s all!
If you want other things to sound too, all you have to do is copy paste this code bit, like so…

You just need to know what variable keeps your designated AudioClip (jumpSound), pass that value to the clip function and then call the play! Be very observant to where you need to put that code, in the case of jump, it just needed to be when you press the jump sound, because once you leave the ground, you can’t make the jump sound, do you?
Now you know quite a lot more about code than you knew before (I hope!), go and play around making other movements, playing more sounds and even changing displacement patterns for your character. Have fun and try to learn more by yourself. If you have any question, just write it down on the comments.

Next tutorial will be about animation with mecanim, stay tuned for more!

¡Unity 3D introductory tutorial Part 1…

Unity introductory tutorial P.1


¡Unity 3D introductory tutorial Part 2.1 moving the character…

Unity 3D introductory tutorial P. 2.1- Moving the character

Live Demo Unity introductory tutorial P.2.2



Continue reading Live Demo Unity introductory tutorial P.2.2

Unity 3D introductory tutorial P. 2.1- Moving the character

What´s up, friends! So, you asked, you have it. I´m back with more Unity 3D introductory tutorials! This time, we are going to learn some basics of c# and how to apply them to make our little pretty character move!
Do you remember last time? We have it all set up for our little simple cutie game to look like something… well, not exactly a game, but at least some playable thing! Hahaha. Don´t you remember? Well, then go take a look at this previous tutorial, then come back here for more action packed tutorials!

Unity 3D introductory tutorial part 1- Setting up the scene…

Unity introductory tutorial P.1

Welcome back! Let´s get our hands dirty. This time there are no assets because everything you need you can get it somewhere else, like in the internet or something like that. There are no new art assets and the modified gameobjects and created script are better done by yourself following the tutorial.
But there is a playable Live Demo of this tutorial! Go take a look if you want to!

Check the Live Demo here…

Live Demo Unity introductory tutorial P.2.1

Let´s open our scene and see how it was…

Lol, remember when we put the Character Control inside the Character Sprite? Have you put thought to it? Do you found some mistake there? Nobody mentioned it, LOL! Well, that´s so wrong, because, if the moving part is the Character Control, when it moves, the Character Sprite won´t follow it!
But why is that? You are surely asking right now. Well, remember the previous tutorial I told you that if something is child to a parent object, the parent object will affect the child? Look who´s child to whose parent in here… that´s right! The Character Control is subject to Character Sprite whims! So, the CC won´t affect what´s happening to the CS. In fact, this is useful if you have some kind of inner movement inside a general movement.
Think about it, if a great machine is moving one direction, and it has a little cog wheel inside, you can make the cog wheel move by itself to its own direction without affecting the great machine movement and at the same time, moving alongside the great machine. Isn´t that awesome!? Of course yes, but not right! We want the CC to control the CS by moving and translating it alongside the playground!
So let´s fix that!

Now we are ready to go! Yeah! But first, let’s add some extra folders! In this tutorial, we will make one new script, and some especial sound effects to our game!
Why SFX? Music is very important for a game to performance satisfactory, sfx and background music mark the beats the player should follow through the game and help them remember even better the game. Haven’t you identified Metal Gear by the way their enemies sound when they found you? Or a level in Donkey Kong Country by whatever tune they play? Keep your game memorable and immersive, begin putting music and SFX early on the development process!

Also, what´s a script? Well, let me introduce you to Unity script creation:

Under Folder option, you can see there are two options, C# Script and Javascript, like I said in the previous tutorial, we are going to learn C#, so go ahead and chose that option while having highlighted the Scripts folder!
You can see the new archive created is different from others you may have seen here before, name it CharacterControl, with uppercase like that and without spaces between the words. This will help Unity to internally name it like something easily maneagable and recognizable. If you add spaces between the words, Unity will still name it without spaces anyway, but without uppercases, it will be something unrecognizable…
Now we have our first script! But again, what´s a script? Well, basically, in programmation, a script is a collection of algorithms (code instructions) that will help your game do something! Right now we have a blank script, pretty useful, isn´t it?
Select the Script and double click it, Unity will automatically open Monodevelop (or whatever code editor you may want to set up, do it yourself, I´m not gonna tell you that because I keep Monodevelop xD). In this predetermined code editor you can see all your Unity created scripts, modify them, even debug them (more on that later).
The first lines are what in programming are called libraries, they contain the syntaxes and definitions of many useful functions for you to use in your codes. These two are the most basic, they allow you to access to commonly used stuff.
I always have confusions and stuff with these things, so whenever you want to use a new nifty function, go looking for them on the Scripting Reference. The Scripting Reference and Unity Manual are your friends, make good use of them.
Once you learn your way around Unity Editor interface and codification basics, you can begin looking for examples or guide on the internet about how to make a specific thing (or ask me what you need and I will codify it for you and give you a useful tutorial to learn why and how it works like that! Like this)…
Go visit my Asset requests for more information!

Clickable object system for Unity 3D


But if you like the self-taught way, you can always do this little useful method to optimize your searches and get something more closely related to whatever you are looking for:
1- Define the gameplay mechanic you want to implement (i.e. graphic interface for displaying life counter).
2- Try searching for the exact term in the internet.
3- If things fail, try with key words. (i.e. graphic interface on screen, and, life counter display). You know, dissect the concepts and search for something more basic, that way, there are more possibilities you will find it!
4- If you found something vague like ‘try putting a Unity GUI Sprite and make a counter variable that keeps the amount of life your character has’ but nothing like a code example to copy paste on your game (the easy way!), then look for similar terms like ‘keeping a count on a variable’ or ‘how to use Unity GUI’.
5- Whenever you encounter a weird looking and seemingly difficult to implement code block, search for its components on the Scripting Reference, and look closely on the conditions you should consider before using it.
That´s all! You can learn by doing, by trying and failing, then breaking something and trying to fix it, I learnt like that, it was fun and headached me, but look at me now, making dummy tutorials on the internet, yeepi!

Next up, we have the header of our code, this defines the class it pertains to:
-Public refers to it being accessible from different scripts than this one (through callings that we can indulge into later, for now, we won´t need it).
-Class refers to the type of script this is, a class is like a component in the Unity-verse, those scripts with this type will be treated like a component and can be annexed to GameObjects (there are other types that can be internally accessed by other scripts, but for now, we won´t need them).
-The next bit refers to the name you put to the script, in this case, CharacterControl, it identifies them among the other scripts, try to be specific on the main function it does, but never so that the name is so long and clunky you can’t even see it! Also, try to make unique names for everything, because duplicated names give error while playing and Unity crashes because he hates copycats!
-The : separates de class from whatever it belongs to, in this case, is a Monobehaviour class (there are other types you can set up, but we don´t need them now), this means it can be accessed and assigned to gameobjects on the Unity Editor.
Always remember every class should begin with { and ends with }, try to keep your {} count in pairs, if there are impair numbers you will surely get an error!
What can we do next? Before making whatever change or adding to the game, you have to keep track of whatever it needs to be done first. Let´s refer back to our GDD (game design document!).
We have the basic things, name and image of the game, game objectives (which will come into play for the next tutorials), the story of the game! (this too, will be applied in depth the next tutorials!), the game locations and props (which we will be adding into detail next tutorials haha), and the game finale.
Next up, we have to define the game controls! These little pesky things you have to activate in order for you to play the game! Nothing important, really, just whatever!! AAAh, don´t do that! Game controls are a very important thing for whatever game you are playing.
The very definition of a videogame is a virtual game with which you can interact, you must have a means to interact, which are the controls, you need to put special attention to these or else, your game won´t even get played in the first place!!
Let´s refer back to Level Up (my go to reference material for designing games ;D)
Let´s talk about controls! Do you knew there was 3 C’s in game development? They are camera, character and controls… Do you remember how we defined camera the previous tutorial? Well, that´s one C out of three! We will talk more about character farther into this tutorial, but for now, it is pretty important for you to know about controls!
There is one important thing to keep in mind when programming your controls, always remember that humans are playing these games! We haven´t get to the point where multi-fingered mutants or many tentacle space squids play our puny games (surely they have better and funnier games though).
Humans (the vast majority) only have 5 short, stubby fingers and mediocre motor skills coordination. You do know what are ergonomics? Well, is that thing you don´t think much about, until you have to design something that’s going to be consumed by a human being and discover no one is capable of using it properly!
Ergonomics is the study of fitting equipment to fit the worker, that us industrial designers and others more keep always in mind while making our creations, unless we want to kill people with them, we have to make them safe, useful and comfortable (unless you want to kill people with love and care xD).
So go ahead and look for more theory on control ergonomics, or just go out and see how players hold and uses their controllers, you can always ask someone if something feels right, a control should be intuitive, natural and comfortable to use, if not, something is wrong!
Don´t force the player to twist up their hands like pretzels, if you want something quicker, take a look at this helpful diagram from Level Up (I love that book!)…

Thumb: flexible with reach. Good for steering and fast response.
Index: strong and fast. Used for response or hold moves.
Middle: weaker but usable for hold moves. Decent reach.
Ring: weak with poor reach. Better for stabilization.
Pinkie: poor strength, reach requires hand support.
Those analysis are based on real studies, folks, so pay attention to them! When you are designing controls, try establishing design rules for your controls schemes based on hand placement (like fps games that use the keyboard for character movement and the mouse for aiming and shooting).
When determining what controls go where on the controller according to basic psychology and ergonomics, you are helping the player to associate muscle movement with a certain action, even when they don´t realize they are doing it!
When dealing with a lot of options for controls (like the multiple keys on the keyboard), try to keep your controls localized around commonly used key groupings like QWERTY or ASWD, so players can quickly adapt to it.
For now, we will leave it like that, I won´t give you the complete cathedra about controls or any other theme, just the bases so you can understand it better, but if you want the complete theory, go look for the book and whatever other resource that may interest you.

So, on to the script, let´s assign a variable for keeping the controls! Uh, what is a variable!? Well, basically, this is a bit of code that keeps some information inside, normally, in C# a variable they can keep numbers (int- integers, float- with decimal point, and others less used) and text (string- words and char- characters), in Unity, that capability gets augmented!

This bit we will need for our controls, yeah, in Unity, even controls are variables! They are of the type KeyCode! In Unity, through C# power, a script class can be considered a variable type when used by another different script class, so basically you can have somewhere a variable of type CharacterControl! Crazy, isn’t it? The public suffix means it can be accessed from the Inspector window like this…

But you can´t see them on your inspector, you haven´t assigned the script to your character, go ahead and do so by click and dragging the script from the Project window to the Character Control gameobject.

For now, we will have just the controls for jumping (saltar) and running (acelerar). Click on the displayable lists where the variable names are…

This kind of variable (KeyCode) allows you to display a list of all the different keys on the keyboard, that way, you can chose whatever you like and try what you feel right for the control! There is another way to assign a valor to a variable in Unity and C#, directly through the code like this…

Immediately after the variable assignation (that´s how it is called, lol), type an = equals sign, this will give you the ability to assign value to the variable. In this case it needs to be of equal type as the variable, which means, a KeyCode type (commonly, through C# implementation, text and numeric variables doesn´t need to be called through their types, so you won´t need to type int.1 and such).
Thanks to Monodevelop compatibility, every time you begin typing something that already exists in the API (search for it if you want to), like an internal Unity function (more on functions later, just bear with me and the term for now =D), an external class, a public and or global variable and such, you can get auto complexion! In this case, a displayable list of different key codes for you to choose from.
Assigning a variable internally is a rigid way to keep your code in order. If you put the variable to Public and the game designer forgets to set a given value on the Inspector window, it can give you a default state for the script to work from.
On the contrary, if you put the variable to Private (or without public suffix, because private is the default here), nobody can access your variable, so if you didn´t assign it, it won´t get a value and the code may break either way! Also, maybe you want your variables hidden and protected so no one else can affect them and corrupt your game or your carefully thought-out code! Oh noes, protect the codes!
But in all seriousness, before putting a suffix to your variables, consider whether you want them to be accessed and modified by other people or scripts, or not, if you need them with constant and permanent values or with things happening without anyone messing with that, then keep them private. You can even search for other suffix in C# documentation, maybe they will work with Unity and help you improve your code!
For now, these two variables need to be public because that will be funnier to work with!
Finally, put especial attention to where we are assigning our variables. Typically, in Unity C#, variables are assigned before the functions or the algorithms in them. In this case, we are putting them before the functions, when they are like that, they are global variables, accessible from other scripts, the Inspector window and also, from all the functions in the original script.
When all the functions can access a variable, we have to be careful what does it keeps and how it is changed throughout the program execution (which is called code compilation). If we want a function to use a variable with a value of 10, but another function changed its value to 9, we are going to have troubles, so keep your eyes wide open for these dynamics.
The other way, which we will be doing later on in this tutorial, are called local variables, theses can only be accessed through the function. Neither other functions, scripts nor the Inspector window can modify or access those value in any way.
There are a variant to this, called function variables, which basically are the equivalent of global variables but accessible only through the function, which will have to be public for other scripts to access it (the Inspector window can’t access it!), but the good news is that internal functions can access them even if the function is not public! Through a function calling, which we will be using later on this tutorial.
Always remember, in order to use a variable in your code, you necessarily need to assign it first, give it some value and then, you are good to go!

Where are the controls for the movements? How are we supposed to tell our character to go left or right and such!? Well, we are going to use a different assignment method for these
You can set it in here…

That’s the Input Manager for the project settings that Unity offers to your player. You can see the option Axis, in here you can find the Horizontal and Vertical axis…

These display many options for you to set the axis to certain controls, by default, the negative button (when axis x or z goes like -1) is set to left or down (because in the occident the norm is to circulate from left to right, so the positive value +1 is set to right and up because you gain altitude when going up something).
Also, you can see the keys for this control, set to wasd (remember ergonomics!) the other values are fine and you don’t really need to tamper with them, but if you are curious, check them out later. In Type you can see the different options for a game control, by default it is set to key (keyboard) or mouse button (there are three main mouse buttons).
Also, the Axis and JoyNum options allows you to choose the settings for a gamepad (joystick), you can experiment with them to know how they work, if you have a gamepad, just plug it in to your computer, wait for Unity to recognize it (it will show you when it’s done with a message to the Console window). Then you are good to go!
Once you are done with these settings, we can continue codifying our controls. Go back to your code editor, and add these three variables under the KeyCode ones…

These three variables will keep the values for the character to move in 3 directions. Yeah, yeah, I know I said it was a 2D game, but since Unity is so cool and everything is 3D in there, we are just emulating a 2D world, while, in reality, we are going to use a 3D physical world! Why is that? Well, remember the viewcube directional gizmo from before?

Well, it says X and Z axis are on the horizontal plane, X gives you right and left, Z controls the depth. But what about Y? Do we really need Y? Of course we do! Our little cowboy character will need the ability to jump over obstacles to get far away or near his enemies!
You can have many 2D games, with various axis controlling the gameplay, the traditional platformer games (think of Mario Bros.) just use the X and Y axis, they won´t play in the foreground or the background, don´t need Z axis!
What about those war games where you control tanks and cars? Vehicles can´t jump off the ground at will (or can they?), unless you use the impulse from a ramp! So you don´t need Y axis there. But it all depends on the context (You will need it when the vehicle jumps off a ramp).
In this case, a human can go wherever it pleases and jump whatever whenever it chooses to. Except if you are playing with a guy in a wheelchair, which would be a far more interesting game than many racing games I know, but I digress!
Well, in our code variables we will keep the values for direction in X, Y and Z axis. The X and Z axis will be controlled by the Axis Input we defined earlier (or Unity if you leave it by default as I did). But the Y axis will be controlled by Gravity and the KeyCode for saltar (jump).
First of all, we need to set up the Function for the character movement, we could just put the code snippet directly under Update, but that would make our code clunky and hard to read.
Good code design keeps an adequate order and ease of read for whoever wants to mess with our code, even yourself will thank yourself after a few months of not reading a code, you can easily forget what it did and how, but having it all with structure and order can help you remember it quickly and easily too!
But wait a moment, what did I just say? Functions!? I have been saying this word quite a lot now, right? I´m so meanie, I haven´t explained yet what it is about! Woah!
Well, I´m not an expert in programmatics, but I can tell you the simple version. Functions are what Unity and many codification languages (like C#) uses to group code snippets that work together in order to give your objects a behavior. In fact, when you attach a script or component to your gameobject, you are giving it a behavior, which combined with more components, creates complex behaviours that together work like Artificial Intelligence!
There are many code controls you can use in order to give functionality to your functions, like conditionants and such. We will be seeing them applied throughout this tutorial series, so it should be better to explain them as they are needed!
Also, When you open up a new script, it comes with two handy functions Unity utilizes as the basic structure for components.

As you can see in this example, there are only two functions, void Start () and void Update ().
Internally, Unity uses Start (as the description says) to initialize values and stuff like that when the game begins. Like the reference manual says: Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
What’s a frame? If you are not familiarized with animation, well, it refers to each time an image is renderized on screen. For animation, it refers to each moment (frame per second) an image is shown on the camera, together they work to make an animated object. In Unity and the game industry in general, it is each moment the game plays, everything on screen is constantly refreshed each frame per second. Haven´t you heard about 60 FPS and such? Frame Per Second is the amount of images being renderized per second, the more the better the game will flow, the less, well you get the idea.
What is enabling a script? Do you see that little cute checkbox besides the script name?

Well, that’s the checkbox for disabling MonoBehaviour on the Unity Editor, which means, that the script won’t work on run play, so its behavior won’t affect the gameplay at all! (useful to check for issues on scripts, or to monitor when they are activated, or whatever you like)
When it’s ticked, the script will work as it is programmed to do. Why is there a checkbox? Well, let´s look at this modified script…

From the documentation: If none of these functions Start(), Awake(), Update(), FixedUpdate(), and OnGUI() are present in the script, the Editor does not display the checkbox.
As you can see, I erased Start() and Update() functions from the script, so it won’t need your permission to be called! Well, in fact, it does, but it will have to have external input to do so, like a call from another script and such.
What does Update() does at all? Update is called every frame, if the MonoBehaviour is enabled. So whatever you put on there, will be working with the gameobject all the time, whatever it is! Constantly ‘updating’.
There are lots more Monobehaviour functions to work with Unity, you can look for them here…

There are lots of useful thingies inside Monobehaviour, but what should catch your interest more is the ‘Messages’ section, where you can find Start(), Update() and all of its friends!
For a function to be called and identified like that for Unity, you need to put the suffix for function Type, it can be the same as the variable types, like int, string, etc. but it can also be of no specific type at all, like these two with Void.
There are special type of functions that make internal process to get a result and use the Return method, but that´s way too advanced for this tutorial anyway, so if you are interested, just go and check the information about that on C# documentation, because that’s a legacy from that language.
Continuing with our codification, and Knowing now what a function is, or some vague idea of it at least, let´s go create our very first function for this character movement script!

I called it Juanita, because I call everything like that (my little plants can testify to it xD), no, seriously, call your functions something decent! Like Movement (with uppercase, it is important!), because it will control the movement of the character, it will help you remember later what it was about, so make good use of it!

Now let me show you a nice secret MonoDevelop has for us! Put three / like this /// before the function declaration (that’s how it is called when you put the function type and its name() like what we did between the {}).

Do you see what I see? The program automatically put this cute comment here for us, describing what you called the function and giving it some kind of context or something. Like with the Juanita example xD (Juanita this instance, lol!). Try naming your Functions differently and have fun watching what MonoDevelop comes up with for your description!

Some of these things doesn´t even make any sense and are funny to read! Lol! But the last one has some logic and even makes sense! The more grammatically correct a name is, the more sense the description will have.
Try something like CalculateLandingDistance or ControlCharacterMovement, you will notice they make sense and even gives you a correct idea of what they are about. That’s because apparently, MonoDevelop takes verbs to tell you what it does, so if the first word is a verb, you are in the correct way, then it takes the rest as the subject of the sentence or something like that, you know, what will be affected by the verb.
This conventions can help you give your functions logical names that will help you improve your codes design and understand better what they do even after months of having written them! Also, if you are not lazy like me, just add your own description in whatever way you want. How to make a comment? Typically just add // before a word and you are good to go. If your comment if of two or more lines, use /* in the beginning of the paragraph, and close the paragraph with */ like that…

Now, after we have had our fun, let´s add the real code here!

In here I’m telling the program direction and directionZ (our axis variables from before), will be assigned the values given by the axis controls. In this little code method, Input is the class unity uses to get external inputs given by controls. The .GetAxis is an internal function of Input, it retrieves the value (from -1 to 1) given by the input axes (like the joystick going right +1 or down -1).
Then we have (“Horizontal”) and (“Vertical”), you will have to remember what name were written on the correspondent fields under the horizontal and vertical axes, that will be used here to identify them. Use something simple, or leave it default, and be sure to write it exactly as it appears there (uppercase sensitive). It is between “” because that identifies a tag, name or whatever that is not a method, a function, a class, etc.

What are they doing here? We have a Class (Input) and we are using a public Function (GetAxis) from other different script (class) than the original one (Input class is not accessible because is internally defined by Unity! Do you know assembly language? NO? Me neither, don´t try to tamper with these then!
So anyway, this is called a class invocation or something mystical like that (I’m nor a programmatic expert!), first you need to put the class name, then a dot. And the function name with () after it (that’s what makes it a function after all, lol!). Between the () whatever value the function asks of you.
Do you know one of those beautiful things that makes me appreciate MonoDevelop even more? When you put the mouse pointer over an code component (like a variable, a class, a function or whatever), it gives you (sometimes) a useful description about what it is, how it is defined in Unity, what it contains, what purpose does it serves!
You can see how Input gets called a class, it’s public (that’s why we can access it!), it’s sealed (we can´t modify it), and it’s an interface that allows you into the Input system of Unity! What about GetAxis? It is a public function of float type, and static (we can’t change the value externally!), and contains a function variable of string type axisName (that’s what are called variables inside the () of these functions, that’s what they are used for ;D).
What does a string function variable does? Well, do you remember “Horizontal” and “Vertical”? those are string variables (using “” to encase words makes them automatically be treated as string, which are a group of characters comprissing words and sentences and paragraphs and such). So what you are doing is assigning to the function GetAxis on the class Input the value you input through the Horizontal and Vertical axis! Yey

MonoDevelop also helps you with auto complexion of code instructions, whener you begin typing, the code editor catches any coincidences on letters, when there is something called by the coincidence, it is showed and you can easily choose from the displayable list so you won´t need to remember exactly how something was called.
You have to know there is something called like that, but the correct orthography MonoDevelop helps you with!

Also, in the case of writing classes and such with methods or functions, you can choose from the displayable list whatever you think can help you get the desired effect, always read the descriptions and conditions you must fulfill in order for it to work properly, if not, you may have errors and not even know why they are there! Be observant and make good use of the little helps MonoDevelop gives to you!

Let´s go back to our variable declarations and change direction and directionZ to public, the click on file and save it, go back to Unity Editor, once you have made changes to your script, unity will need to refresh itself, so changes can be applied to the game project.
A little wait circle will appear at the right lower corner, once it disappears, you can continue editing your game. Sometimes changes will be so much, the engine will freeze over a little, and you won’t be able to do much while waiting. It can depend on your system power too!

Then go ahead and click the play test button, and with the Character control gameobject selected, search for the Character Control script. There you will be able to see the variable fields DirectionX and DirectionZ (notice how naming them with uppercase helps the Inspector to name them correctly and easily identificable!).
You can now test your code! It now has some function and is no longer just a dumb object, click on the directional arrows on the keyboard o the AWSD keys and see how the variables change its value!…
What did just happened? Did your code worked? If it worked, then congratulations, you are a god of programmation!! I will tip my invisible hat to you, because in no way this can work at all!! Why is that? It didn’t worked for you? =(
Well, I have good news for you, it is not your fault =.( I forgot to mention that if you don´t call your function in one of these internally controlled function of Unity, your customized functions won´t work!
So let´s fix it and go to Update(), because we need this one to be constantly checked and updated, and add this code…

To call a function, as we already saw with the Input class, you just need to type its name (that’s why it is important to give significant names, lol!) and immediately the () which will be used to assign values if your function has them (mine doesn´t). Also, you should be accustomed by now, but I never mentioned it, but the “;” is used to end a code instruction so Unity can know where one ends and other begins and avoids errors!
Go ahead and test it now!

But wait! It is doing nothing at all to the character! Yeah, right, we have some numbers doing something or the other, but I really don´t care about that! Do I? Well, you should! This means we are getting external input from the player (in this case, you!) and the program can do something with that information. Right now, it can do nothing, we haven’t programmed it yet. So Let´s fix that, shall we? (Also, don’t forget to change the variables back to private, we don’t want anyone tampering with them!).
Go back to the global variables and add this…

This one is private too, it will be controlled internally, but is of a new type! Vector 3, this type is funny, I like it so much. It can keep three values at the same time. This time, we have a Struct , another C# legacy that helps Unity with its stuff. Think of a Struct as a structure (for what it is called after) that keeps and organize values.
Sometime later I can make a tutorial to show how useful structs are! You can use them for keeping references to different items, very interesting. For now, you should know something about Vector 3. There are vector from 2 to 4, each one useful for saving from 2 to 4 values inside. What´s a vector? Remember those colored cones in the navigation viewcube unity has to identify axes? Well, if you remember something from vectors in your physics class (I do not, but if you do, tell me! XD), they are the direction a force take!
In this case, they are somewhat similar, but different still. In a vector you can keep an axis value or something like that. Vector 2 has x and y axis. Vector3 has x, y and z. Vector4 has the same three axes from forever, plus one extra W! Useful for whatever a W axis can be used for.
So this Vector3 move will keep our three axes values, which we will assign through this code you can see here…

The declared variable move is assigned the value from a new Vector3 (that way, you can access to all the three values on move simultaneously!). This Vector3 will have in its X and Z component the values you input from direction and directionZ, leaving the Y component like 0 (or else, it will begin floating randomly, we don’t want that! LOL).
Let´s test it, first make Vector3 move public, then go to the Unity Editor and click on play test. At first, move will have its three values on 0, but if you press any directional key (assigned in the axes), you will see it change its x and z values! It works! We are almost there, but there are few things we need to change first to make the character moves! (remember to make move private again!)

First of all, the character can´t move because we haven’t assigned it a Character Controller component yet! That’s what Unity uses to give us control over a playable character, that’s right, Unity does all the work for us once again (I love you, marry me, Unity! The wedding is tomorrow xD). This component gives our character weight and mass, collision and the ability to move!

Now, we have to pass to our code this component, because, that way, we can control it from the script and make it move as we please (like a master of puppets, muahahaha!)

Here you can see that under our public class CharacterControl we added the public variable CharacterController CharaControl (that’s a lot of redundancy, but it’s fine, the more relation they have between each other the more easy they are to recognize them xD).
CharacterController it´s a component that also is a class in a script that we can use as a variable type. Also, I added one extra code, in case you need a component in order for a script to work properly, like in this case, it´s a good practice to put over the class declaration the method [RequireComponent(typeof(CharacterController))] this will assign automatically to your gameobject the component of type (or called) CharacterController!
You don’t even need to think about it, it will be added the moment you add this script. Just try it out on whatever empty gameobject and see how it works.
Also, you won´t be able to quit that component from the gameobject unless you quit this script first, that way, you prevent fools and forgetfulness to wreck your code and make the game have bugs! Nice~
Just one more detail, remember our character has a CapsuleCollider component we added the last tutorial? With CharacterController you don´t need it anymore to make it impenetrable, but don´t go and quit it either, because without it, you won´t be able to detect collisions!
Since right now collisions aren’t our business, you can leave it like it is, later we will mess with it. Now with this new CharacterController variable declared, let´s go back to our function! Add this code instruction….

TransformDirection is part of transform class (the same that controls that Transform component every gameobject has in the scene!), it takes a Vector3 that possess a local space value to transform it to a world space medition. Finally, it assigns the converted value from local to world space to the same velocity variable that we don´t have yet, so this time the movement is absolute and not relative to the local space of the gameobject.
I really don´t know what all of that means and what it is like that, but that´s what the Reference Manual says and I just obey it xD. Whatever, you may have noticed we have a new velocity variable we haven´t named elsewhere, that´s funny. Isn’t it?
Well, where do you think it should be added? Also, you may have noticed how Unity marks this one in red!

Let´s take a break and see how our little code fails! Yeepi! Click on Run, choose Start Debugging…

Maybe you noticed I say “bug” a lot! What’s a bug? Prepare for a bit of historical information! Back when computers where more analogous than digital, and only the five more powerful kings could own them (ok, that never happened, thanks Simpsons xD), there was an incident where one of those perforated cards programs wouldn´t run well, and the programmer was all confused, because he did everything right! He cried, he blamed, he blasphemed and when all options were out, he decided it was the machine fault! So he opened it up and found inside of it a little bug trapped inside the transistors and such. From there on, whenever you have an error on your program, you can call it a bug!
Right now, our problem is because we forget to declare a variable somewhere, so you can see Unity shows us everywhere the error occurs, that we have make something wrong. Unity is not coy to embarrass us, isn’t it? Just go ahead and add the declaration of a Vector3 velocity variable where it should be, then under move = new Vector3 (directionX, 0, directionZ); write velocity = move; for now it will do with just that. Debug again, that should correct all your wrongdoings xD. (yep, it was so totally your fault, not mine xD).

Now, in order for our code to affect the CharacterController component, we need to call a special function this class has! Right under the velocity assignation, type this bit of code…

CharaControl is our variable for CharacterController, it has this function Move (which receives a Vector3 value). We passed the value from velocity and multiplied it by Time class function deltaTime (pretty much you can get what everything does through their descriptions!). Using the class Time you can create many interesting counters, clocks and such, but that’s for another tutorial ;D.
Why do we need to multiply our velocity variable by the time it accumulates through each frame? That’s easy, and it will come on the test (XD), that way, the increment won´t go up infinitely and cause your character to move to Speedlight levels or something. Go ahead and try it now!!
Ups, it doesn´t work, again xD You forgot to add the CharacterController component of the playable character to the script field! Just click and drag your character control gameobject to the designated space and that´s all!
Now, to make sure you assigned the correct gameobject to the field (Unity helps you avoiding the assignation of a gameobject that doesn´t even has that component!), just click on the field and see how Unity highlights in yellow the gameobject assigned! It’s the correct one? Then go ahead and test it out!

Well, the character does moves! Yey! Slowly, but sure… but there’s a problem with his movement, it doesn´t face to where it is going, just keep facing up front! That’s not useful when you have to backtrack or go to the sides, it doesn´t even move like a tank! Also, the controls are somewhat inverted, everything is bad! But at least, you can move (xD).
We need to add some more code to make it so, but for now, we have finished this lesson, because that pertains more to physics control and metrics!
Another problem, maybe, is that your character is behaving weirdly and maybe falling over the ledge without you knowing why, right!? Well, that means you need to play around with the CharacterController options.
More specifically with the Radius and Height, I used a radius of 1 and a height of 3.8, because my character is too small to fit anything else. Pay close attention to how a wireframe cylinder scales itself after you change these values, when it covers the entirety of your character, without going too far away from it but also just on the edge between its feet and the ground, you are good to go! Now try moving around and that’s all!
Also, this tutorial has exceeded today’s actualization, so I will split it into two, wait for the continuation and the complete Live Demo next week!
For now, don´t forget to save your work. See you next time, ~Chaozz

¡Unity 3D introductory tutorial Part 1…

Unity introductory tutorial P.1


¡Unity 3D introductory tutorial Part 2.2 moving the character… Coming soon!

Unity 3D introductory tutorial P. 2.2- Moving the character

Welcome back! Again we have no downloadable assets because everything you need you can get it somewhere else, like in the internet or something like that. There are no new art assets and the modified gameobjects and created script are better done by yourself following the tutorial.
But there is a playable Live Demo of this tutorial! Go take a look if you want to!

First of all, last time I didn’t mentioned it, but this is a pretty crucial point to take into account, also, there is interesting theory you should know about. We already have collision detection on our character (CapsuleCollider and CharacterController), but do you know what that is or how does it work?
You have to determine where and how the character is going to interact with the world through collision so the metrics can work adequately. Collision is determined from a primary point on the character model. There are generally three locations on a character from which the player can interact with the world:

The head: This point as the main collision point can cause problems, specially when determining ground collision (isGrounded character controller function on Unity). The character can appear to not be rooted to the ground, giving the appearance of slightly floating.
The feet: this may seems the logical location for collision detection, but it can cause issues if it is used to determine where a power-up is collected (for example, if it is mid-air, the character will have to jump to collect it).
The torso: according to Level Up, this is the best place to determine the character’s collision with the world. It provides enough coverage for both halves of the body and feels ‘right’ when the player runs or jumps through an item for collection.
But let me tell you a secret, this won´t matter as much in Unity! Yeah, you still have to consider all those points of collision, an all body collision may be needed even. Especially if you are using a completely rigged 3d model: it can extend arms and touch objects with its hands (or even forearms, upper arms, fingertips!), it can extend legs and kicks some stuff, it can even extend its head and touch the ceiling. Whatever can be an important collision point for gameplay!
You may not know about this, especially if you are just beginning with game design and are young, but before, people only had at its disposition collision boxes, circles and sometimes capsules, and they had to be placed in a way it covered the majority of the character’s sprite so everything touched by the box could be interactable and the player could see it as the character touching something and not some mystical invisible box.
Well, those days are over, because in unity, you can have as many mini colliders as you may want! Each fingertip with its own collision box (even cylinder, or even better, mesh collider with just the shape of that fingertip!). Each leg, each arm, whatever you want can have its own collider, according to its particular form, and move alongside with it (through child-parent relationships). Whatever can have its own collision detectors so you can have micro interactions alongside your model.
Think of a giant troll touching everything in its path! Stepping over townsfolks, grabbing houses, eating a little sheep, whatever you can dream of can be done! Of course, all those micro collisions will consume its share on resources, but you can worry about that when you get to it.
For now, we have already put our collision detection on this character of ours, remember CharacterController, right? Since this is a very simple 2D game, we won’t indulge in such things as micro collisions on fingertips, we just need something that will cover the entirety of the sprite, something simple, since a 2D game can do without those complex things.
However, Unity manages simple collision detectors in the form of the various Colliders it has available. One of these is through the CharacterController itself, also, the RigidBody has its own kind. But the most easy to learn are the ones below and including then BoxCollider, because their detection is more easily controlled and programmed by a beginner.

Remember we had a CapsuleCollider on our character? Well, let’s change it a bit, because right now we won´t indulge too much on that aspect (first we need to configure the items and props it will collide with, and that’s for another tutorial! Wait for it).
First of all, mark the checkbox on your MeshRenderer, so that you can see the CapsuleDrawn By the collider, and next up click on the little cog wheel besides the name and select Remove Component. We won´t need that pesky capsule anymore! Do the same with the CapsuleCollider and the Capsule (Mesh Filter). We don’t need no more of these things!

Make the CharacterController as slim as you can modifying the Radius. Remember that BoxCollider from before? Select and add it to you Character Control gameobject

We need the BoxCollider it will cover more ground that the capsule (because of its shape). Next up, change the BoxCollider to trigger by marking the checkbox on isTrigger (this will allows the collider to be penetrable by objects, while at the same time, detecting collision). And play with the size fields until you have something that covers around the middle body and head of our character, while at the same time, getting out of the CharacterController zone.
When you have both CharacterController and whatever other Collider in the same gameobject at the same time, the first tend to block the latter, making it unable to detect collision. Besides, we don´t really need the CharacterController to cover up all the character sprite, that would make it difficult for it to navigate in narrow spaces. You know how in real life you can always compress your arms to your body so that they won´t bother you in these situations? Well, this is the equivalent of it.
Also, it’s good to have the collider a little outside the body, because that way the collision detection is more natural; not so much that it appears the character has psychic powers! But enough so that you don’t really need to stand directly up and cover all the things you need to collide with.

For now, we are fine in the collisions department, our character is ready to begin colliding with things! But our focus right now is only on movement, so let’s get going with that!

Remember last chapter how Gun McShooter was sleeping soundly and dreaming of black waves, then all hell broke loose and the train with the money exploded? Whew, do you!? I don’t! Tell me more! Hahaha, because I remember something like Gun being unable to turn around and just walking around from side to side and such, wasn’t it fun?
Kidding! Don’t kill me (yet!) Now, I’m going to show you, not only how to make him move differently, but also, how to move faster, jump higher and even fall again to the ground! Put your gun belt and prepare yourself for some more coding action!
Well, now that we are going to add some physics controls to our hero which in turn, will serve as the metrics controls too! We need to define some basic things that will improve or difficult our gameplay, that´s right, the character will affect directly into the players experience of the game!
You have to know and always remember that all gameplay flows from the main playable character (it can be a person, vehicle, animal, an abstract object, even geometrical ones like tetris! Whatever you move, that is the main character!). You have to think about the player’s relationship to the world:
Its height, reach, means of transportation, longitude and volume. Whatever you can think of that constitute the proportions for metrics.
While moving, the character must be able or unable to reach some gameplay objects (whatever the character can interact to, is a gameplay object).
There are distances for climbing (you have to jump? You can climb directly from the ground? You need some force to help you climb?); walking (how wide must a path be for the character to walk through it? How steep the ground until the character falls back down sliding? How far can you go until the character tires itself by walking or running?); jumping (what can you reach in a single jump? Can you jump twice to reach farther? Can you extend your jump by running? Which direction can you run, vertical, horizontal, diagonal?); crouch (do you have to crouch to get into small spaces? Can you reach other superficies and objects by crouching?).
And whatever else you may think. Always think first on the action and immediately after, the conditions this action can affect gameplay.
Just remember, walking alone is not gameplay, but the variations of conditions in which you can walk and the alternatives you can have to walking that will allow you to reach farther and better some places in the playable world!

Metrics are very important to players, because they use them to gauge movement and reaching distances just “by eye”, even if they are conscious of it or not, they will catch up to it sooner or later and try to exploit it to their advantage.
There are few things more satisfactory than knowing how you can mess around with metrics and controls to reach hidden places and secrets. I remember always trying everything in my reach to play through a zone faster, or breaking some limit, or achieving a trial with less effort. You can feel a pro just by getting used to these metrics and controls, or like a dummy for not knowing what to do with your character.
It all depends on the design, so think carefully about these aspects and play with them consistently so the player can enjoy the game and have some good time trying to best himself in whatever trial you put him through!
In order to correctly asses metrics, consider the basic height of the character, the speed the character travels, the height it can reach, how much it can fit in a place, so on and so forth, it all depends on the context of your game.
I can suggest you to take your character as the measure unit, like ‘5 character units (CU) wide’ or something like that. Also, when designing you environment, props and enemies, make sure to use your character as the base unit to scale them up. Your enemies can be like ’10 CU of height and 5 CU width’, and some pathway like ‘3 CU wide’. Always keep this in mind and the world around the player will feel right.
If you don’t believe me about the importance of metrics, I will suggest you to take a look at that creepy Lara Croft videogame (I think it inspired the movie, but I´m not sure), where she killed a bunch of innocent tigers in the Himalayas. In that very same game, her house was this gargantuan mansion where she could take a bath in the water basin or cook herself in the oven!
It was bizarre, like some kind of Gulliver with guns and polygonal boobs xD. But I can understand why they did that, from a designer point of view, maybe their collision detection weren’t so perfect as what we have today, and in order for her to fit in her house, it should be like 10 CU wide in scale. Weird!
Fortunately, Unity is far better at collision detection, so we can measure correctly and make pretty games at the same time!
In this case, we will leave these options free for the game designer to play around with…
-Height: the height of the player character.
-Width of passage: usually wider than the player character.
-Walking speed: how far the player travels per second or unit of time.
-Running speed: how far the player travels per second or unit of time but faster.
-Jump distance: usually farther than a walk, but not as far as a run; can also be based on the player’s width (like 5 CU across or so).
-Jump height: based on the character height, a jump can be half the height of the character, while a double jump can be twice as tall the character and so on.
-Melee attack distance: usually not much farther than the length of the player´s arm and weapon.
-Projectile distance: this can be as short as the player´s reach or width to as far as the player can see.
An example of how to apply this, can be seen in this image taken from Level Up…

The cliff ledge shown in the above graphic is obviously completely unobtainable with a normal jump/ double jump distance. So the player will know that they won´t ever be able to reach this height and will look for another way to get to their destination, a well thought out obstacle!

For this very same reason, we are going to stablish in our nifty code some variables that will allow us to modify the properties of physics and scale it during play test in real time! (when we have the code that will make it work, you can click play, then modify the variable values to make them affect the movement in real time, so you can know which values are right and so on).
What we will need to add are the following variables…

These variables have names that are self-explanatory, also, I added some default values in case you forget to set them in the Inspector, they are public so that you can do so.
Now, for what are they? We are going to use them to construct our rotation control for the character, that way it can turn around and face different directions! But they do need more friends to make it so! Just add these other variables, this time, inside the Movement() function, just above whatever other code you have there, because variables are better declared at the top of everything…

They are called somewhat close to what they do, but I can’t really explain what they do without showing you the instructions where they are used! So let´s add some more code to this!

Wow, we added some new instruction we haven’t seen before! You learn new things each time you open one of my tutorials (XD). Well, that little thingie if (CharaControl.isGrounded) is the application of a helpful conditional instruction called ‘if’, have you heard that phrases “if you eat vegetables, then you grow taller!”? Well, this is like the same thing, only with a twist! If you do whatever condition is written inside the (), like CharaControl.isGrounded, then whatever you encased in the {} below the if condition will be executed!
But what about !CharaControl.isGrounded? Do you remember that variable that kept the CharacterController of our playable character? Well, since it refer to a class, and classes tend to have functions, isGrounded is a Boolean (yes or ! not values) function. When it doesn’t have the !, it should check for a positive value (the character should be grounded!), but if it has it (! Not symbol before the variable name), then it should get a negative value (it is floating and not grounded at all!)
Also, it checks whether your CharacterController is touching the ground or not, that’s why it is important to have a ground and make sure the CharacterController is exactly the same height your character sprite is.
This basically means that, whenever your character is not touching the ground, it can move with velocity being equals to move * moveSpeed (since we don’t have gravity activated yet, so we won’t be able to make sure it is always touching the ground while not jumping!). Remember what was velocity in your physics classes? Well, me neither, it was something like distance / time or something like that (xD I’m not physician either, but I make do with what I have!). Move is supposed to be the distance (like when you triangulates the walked distance in a map? With the latitude, longitude and height or something like that, I’m not geographer either!). MoveSpeed should then be the time, but whatever, it works xD.
Now erase the velocity = move; code you put the last tutorial and click test play! How was that? Did it moved more quickly? Try changing the MoveSpeed value and see what happens! That’s fun! You can move at whatever speed you want now, just changing this thing! Yeah!
But what about the other variables? Well, each one has its use specially for changing the problem with the facing of character while it moves. Let’s see about that. Add this code just above the CharaControl.Move (velocity * Time.deltaTime); and play close attention to the localization of velocity = transform.TransformDirection (velocity); an instruction we already have set…

We have assigned the value of velocity.z (in its z axis) to ForwardAmount, then did some kind of mathematical operation (class Mathf, function Atan2, I really don’t understand what it does, but you can check on the Reference Manual and see if you have better look xD), that plays with the axis x and z of velocity.
Another mathematical function (Lerp) that plays with all the other variables we assigned first (StationaryTurnSpeed, MovingTurnSpeed, ForwardAmount), because reasons (I really don’t know, I just followed an example on rotating the transform of an object and go on with it xD). But I can say Atan2 gets you the angle distance between point a (velocity.x) and point b (velocity.z), so that you can get how much distance is needed to cover that up when rotating your gameobject. Lerp gets some kind of value for setting the speed, so the rotation can be gradual and not sudden and choppy!
The interesting bit is the transform.Rotate, transform refers to the Transform Component of the gameobject the actual script is attached to, is like a predetermined variable of type Transform you can use to avoid assigning it yourself, Unity detects it automatically. The rotate function refers to the Rotation fields on the same Transform Component, it passes through the values you set as angle an makes the rotation according to that values.
Now you are ready to try it out! When you advances forward, the character goes that direction, but whenever you press any other direction, left, right or down, the sprite rotates, taking the camera with it and changing its facing direction! This can work, if you want a tank like control on your character.
However, if you want something more natural and useful for a third person shooter game, the character needs to be able to go up, down, rotate when going to left or right, and also, maybe being able to go left and right without rotating.
There are many complicated ways to do this, but I have one simple solution using only the code we already have plus some little aditions. Do you want to see that? Then add this code to what you already have…

As you can see, we still have ForwardAmount = velocity.z; and TurnAmount = Mathf.Atan2(velocity.x, velocity.z); assignments, only enclosed within the conditional if (Input.GetAxis (“Vertical”) == 0) {}, here we are checking whenever the player is not going up or down (Vertical axis is not -1 or 1), the instructions on this code will execute. The ==0 is the comparison we are making.
When we need to compare a numerical value (Input.GetAxis retrieves a float value, which means, numerical values with decimals) and see if it does have a given value (in this case, by pressin Vertical axis you can get 1 or -1 value, positive going up or negative going down), we need to add < (minor than), > (major than), == (equals to), <= (minor or equals to), >= (major or equals to) or != (different to) signs. If you want to learn more about this, look in C# documentation about conditional instructions and comparison signs so you can get a clearer idea about what they are all about.
In this case, when the character is just standing there, we can rotate it by pressing left or right. An extra ability is that when you are going up or down you can go sideways in that direction by pressing both Horizontal and Vertical axis. That’s great, isn’t it?
The “else” part is the alternative behaviors to what happens when the condition in “if” is not happening in the game. You can have as many “else” as you want (many alternative behaviors) by writing “if else” instead. This is like saying “IF you do have eggs for breakfast, you can bake them, IF ELSE you don’t have them, eat ham, or ELSE if you have neither of them, take a bowl of cereal”. Now it have more sense, isn’t it?
Go ahead and test the game! You can see how when you press up, the character goes normally up front, when you press down it backs down facing the same direction (useful if you are shooting enemies while at the same time, trying to get away from them!).
Also, when you only press left or right, the character rotates and changes direction of facing. This is going to be useful to correctly navigate maps and such, because now you can see where you are going and not just going sideways while always facing the same boring direction forever!
And the extra ability happens when you press a combination of Vertical and Horizontal axis, try it out! Now you can go sideways while advancing or retreating, perfect for dodging enemies, hiding behind obstacles and looking for an opening to begin your attack!
Try changing the variable values and see what happens, experiment with them until you got the correct combination. If you do this during gameplay, maybe you may have noticed the changes won’t stick when you stop the play test! Oh no! How are you supposed to set the right values now? Well, I will show you a little nifty trick.
Remember that little cog wheel beside the Component name? Change values and click on it while play testing and choose Copy Component, then stop play testing and click on the same cog wheel, choose Paste Component Values and you are good to go now! You can do this with whatever component you may want to change, but remember doing it with just one at the time, because it only works like that.

Now we have learned the basics of coding with Unity and C#, established controls, collisions and make our little cutie character move according to our will, muahahaha!! What’s left to do in this tutorial? Nothing, goodbye, I have to sleep…zzzzzzzzzzzz

Hahahha, just kidding! We haven’t added the acceleration and jump stuff (we already have the controls, don’t we?) and I promised you to introduce the music controls too! So let’s go on with some final details!!

Let’s begin with the dash movement, do you know what we need first? I will give you some minutes to figure it yourself. Remember we always need to manage variables in order to get values and play with them!
Do you know the answer now? That’s right! Variables! (I fell like Dora the Deported Explorer xD).
Let’s add the variables… You can see I added a little title comment, I like to tag my stuff like that so I can classify it better and know what everything does, try it out yourself ;D.

Then add and modify the if (!CharaControl.isGrounded) part under Movement() function, that is where we control the main movements of our characters, so everything that modifies it should affect here!
Erase the “!” from where it is and add an “else” condition, where you tell what to do whether the CharacterController is grounded or not. If it is floating (while jumping, for example) it can’t use the dashSpeed to increase the velocity, because you can’t dash without touching the ground (unless you have motors and are an airplane or something!).
If it’s touching the ground, dashSpeed is going to be added to MoveSpeed, increasing the velocity! (that’s why it’s important to have a base MoveSpeed not so much quickly as the dashing one).

Now you have to make a function that will control the dash increment, you already had assigned the button for it, do you remember it? The if (Input.GetKey (acelerar)) part will check if Acelerar key is pressed (GetKey checks on the keyboard keys, because they are not axis like with GetAxis).
If the key is pressed, dashSpeed will be assigned the MoveSpeed value multiplied by dash amount (it should be like a percentage of .2% or something like that, a low value but higher than 0 so it can have an increment!).
The “else” part will return dashSpeed assigned by 0, which means, if the acelerar key is not pressed, there will be no acceleration.

The final step is to call the function from the Update() function so that it can constantly affect the movements of our character.

And that’s all! You can even assign the acelerar key from the Start() function so it won’t be empty if you forget to assign it like so… You put a conditional to check if accelerar is equals to KeyCode.None (which means, it has an empty value), if it is, then the default value will be assigned, if not, then it is left as you put it. Now you can play test it!

You may have noticed the character is not accelerating at all when you pressed the designated key, right? Also, when you go out of the terrain limits, the character won’t fall over to a certain death! Well, that’s because the character doesn’t have any gravity to speak of! We need to set it up first! Add the following variables!

They will control how much force the character jump has, and how much pull the gravity that influences it will have.
Let’s go ahead and put default values to the jump key input…

Do you have any idea where the jump value would affect out character movement? Think about it, I will wait for you….
Are you ready? Remember the dashSpeed influencing over velocity? Do you think jump values affect the same? Woah, you are right! (I know you were thinking about it, I’m psychic like that ;D). But it won’t affect the entirety of it, like dash did, because we only ever jump up, but it can combine with other movements to, because it affects the character displacement in the up/ down axis, what’s that axis?
Well, remember this instruction… move = new Vector3 (directionX, 0, directionZ); and then this other velocity = move * (MoveSpeed + dashSpeed); we assigned the displacement in X and Z axis to move, which in turn was assigned to velocity, but we left the Y displacement like 0! Not anymore! Add this code between the others you already have (be careful not to write them down again! Be observant and learn to identify what you have and remember it even if for a few hours =P).

That’s right, velocity.y (the axis Y in velocity that wasn’t assigned by move!) will be assigned by directionY! That’s all, you made it! No, wait! What did you do? Where are the variables we have just declared for this? Aah, do you really thought they were going to be used directly like that?
Nope, direction will keep the value they return, but we need to make a function for it…

That’s it, her you can see we assigned jumpSpeed (and dashSpeed) to direction, but only if the character is already on the ground (if it’s not, it can’t jump again, can it? Unless you want double jump, but this is no magical cowboy, sorry xD).
If you have already jumped, but still want to press saltar key, then you are out of luck, because here we have assigned some value to gravitySpeed (it will increase according to deltaTime), and multiplying it by gravity, both will be decreased from directionY.
Your character will only jump so far (to reach the designated value on jumpSpeed or that plus dashSpeed), then fall all over again. This is the part where you can assign the double jump, assigning jumpSpeed again to directionY.
And even if you don’t try to jump again, you are going to start falling. The good news is that you can still move sideways, so you can do horizontal jumps in whatever x or z direction you want to!
Now you have set up successfully dash and jump moves! Go and try them by yourself, remember the controls you assigned and have fun! Don’t forget to tweak your variable values so that the character behaves as it should ;D
There’s only one more thing to do, the music! Right now, we are just going to set up SFX, that will sound when you walk and also when you jump. Search for sfx that you like from whatever videogame you want and then pass them to your project asset folder SFX.

Now add an AudioSource Component to your CharacterControl gameobject. This will make your gameobject into an living (virtually) speaker! Leave the default values.
You can have a lot of applications of this component, like people walking around listening to loud music, tv speakers, stereo speakers, whatever, try it out when you want! Also, we will need it in order to set some SFX to our character, it will be recycled with every sfx it needs!

Just to be sure, add this extra code above your class definition, so that everytime you add this code, an AudioSource Component will be added! If you forget to do so, don’t worry! Taking this kind of precautions allows you reutilize the same script over and over without having to remember much about it.

Now it’s time to add our well known variables for the audio control! AudioSource needs to things to work correctly as a recyclable component. First, assignment of AudioClip type variables, which will contain the sfx clips you search for in the internet! I called mine stepSound (for walking) and JumpSound (when jumping). You can even ad one for dash and whatever else, once you learn how to set it up for something, you can set it up for anything!
The second things is AudioSource type variable, it should be private, because we are going to assign it internally (you can assign it publicly too, but let’s try this one so you learn how to do it yourself!).

So let’s begin with assigning AudoSource, when done internally by the script itself, it is called Initialization (or something along these lines). Basically we tell the script to assign a declared variable (AudioMove in this case) a given component this gameobject should have. If we know it has it, we shouldn’t have any problem (that’s why we make sure this script will always require for our gameobject to have it and add it itself!). But if you forgetfully forgets to add it up (or deactivates it through unmarking the checkbox!), the script will behave erratically and have bugs and make everything else explode!!

Be very observant of your codes and what they need, a well thought-out script is a happy script xD.
Now GetComponent is not a function, variable or conditional of any type, it is a method Unity has defined internally (its own API) in order to control these kind of things like getting external components and such. Whenever you use it, you should add the component name (class) between the ();
Once you are done, you have successfully initialized a component type variable, now we can freely use it!
We need to assign sound when the character does move and when it jumps. Do you remember where we control each one? That’s right, the functions! Go to Movement() and add this code where you see it chilling out…

The “if” conditional checks whether velocity in X and Z is different (!=) to 0 (which means, it is moving in some way! But at the same time, it checks if CharaControl is on the ground (if it’s not, you can’t really step, right? Your feet can’t make a sound over the air!).
But how are we checking various things simultaneously!? Well, play close attention to the && (and) and || (or) symbols, they are used to add or substract conditions to instructions like these.
If you have && then the instructions at both sides of the symbol will be considered (you should be moving up or down while on the ground). If one of these is not valid (you aren’t moving up or down on the z axis or you aren’t on the ground), then it returns false and the instruction in the code block won’t execute.
However, the || symbol checks if whatever instruction at both sides of the symbol is valid (you can be walking on the ground up or down or walking on the ground left or right). If one of these is, then the instructions in the code block (between the {}) will execute!
Also, to facilitate reading and make it clearer to the code what you are trying to do, don’t forget to group instructions around symbols inside (), that way you can easily know what it should accomplish and the code won’t get confused. You can see (velocity.x != 0 && CharaControl.isGrounded) and (velocity.z != 0 && CharaControl.isGrounded) are both encased on their own unique (), because they both have inside a && symbol, but both are grouped around a || under another pair of ().
Also, the if (!audioMove.isPlaying) {} checks whether the AudioSource type variable audioMove is currently playing some sound, if it isn’t (!), then it will execute the instructions insided the code block: audioMove.clip function will be passed the sound that stepSound keeps, and audioMove.Play() will be executed, playing the designated sound. And that’s all!
If you want other things to sound too, all you have to do is copy paste this code bit, like so…

You just need to know what variable keeps your designated AudioClip (jumpSound), pass that value to the clip function and then call the play! Be very observant to where you need to put that code, in the case of jump, it just needed to be when you press the jump sound, because once you leave the ground, you can’t make the jump sound, do you?
Now you know quite a lot more about code than you knew before (I hope!), go and play around making other movements, playing more sounds and even changing displacement patterns for your character. Have fun and try to learn more by yourself. If you have any question, just write it down on the comments.

Next tutorial will be about animation with mecanim, stay tuned for more!

Live Demo Unity introductory tutorial P.2.1



Continue reading Live Demo Unity introductory tutorial P.2.1

Unity 3D imported 3DS Max model test

Hello! This is a random post xD By request of a Pakistani friend I did a skater guy totally modelled on 3DS Max, rigged and animated too! I had so much un posing him to animate it. I Have discovered the animation workflow of 3DS Max is so wonderful, that I liked it so much!
Then I tried it out on Unity because it s funny!
So I have decided to make a nice tutorial about modelling techniques (aimed to improve topology), rigging, skinning and animating on 3DS Max and the workflow of importing and mecanimating it n Unity! 2 x 1!
Stay tuned for it!

Hola! este es un post random a mas no poder! Por peticion de un amigo Paquistani, modele un skato de la old school completamente modelado, riggeado y animado en 3DS Max! Me diverti tanto posandolo para animacion, que he decidido hacer un tutorial completo sobre el tema… en algun futuro proximo ;D
Tambien incluire el workflow para manejarlo en Unity usando mecanim! tutorial 2 x 1!
Esten al pendiente ;3

Enlarge

DSC_0129
Here you can see all the nodes I connected on the mecanim system, they simulates some kind of skating cycle for my skater guy xD

Unity 3D tutorial introductorio P. 1

Hola amigas y amigos! Este tutorial fue pedido por un cool amigo extranjero (directo desde Arabia!!) que me encontró por la página de Facebook! Él quiere aprender a usar Unity 3D a través de un recurso escrito y con buen inglés, pero ya saben que yo los quiero, mi bella lengua nativa y todo eso, uy, cómo me gustaría poder traducir esto a lenguas indígenas (T.T), en fin, así que a la vez que subir la versión en inglés, podrán disfrutar esta otra en español súper chulo!
Este será un tutorial exhaustivo que cubrirá todo lo básico de la interfaz gráfica de Unity y su editor, y trataré de publicarlo cada semana o algo así. No seré muy frecuente (a menos que sea muy popular y mucha gente me anime a sacarlo más a menudo, vamos, únanse y denme likes xD), pues es una tarea tremenda, ya que tocaré temas delicados como los básicos del lenguaje de programación c# y la API de Unity!
Que es lo que domino, si alguien quiere javascript, talvez algún día le aprenda, pero no me gusta mucho el javascript, no es tan riguroso y me llega a confundir, pero haré el intento xD. Esos tutoriales de código estarán enfocados para gente con 0 conocimiento en programación, si eres de esos, te interesará!
Así que, quieres programar tus propios videojuegos, que sean bonitos y que sean funcionales, además de poder distribuirlos en varias plataformas para jugar? Unity es para ti!
Lo primero que ocuparás será el Engine de juegos Unity 3D 5x instalado en tu computadora. En mi caso, instalé la versión 5.5.0f3 (algo más moderna, pero ya no sé en cuál van!), porque a partir de ahí el WebGL está más optimizado que en versiones anteriores, pero tu puedes descargar lo que se te dé la gana!
Se requiere hacer una cuenta para descargar e instalar el programa, y cuando ya lo hayas hecho, puedes volver a seguir aprendiendo, jejeje.
La versión personal es buena, mientras no ganes millones ni tengas miles de personas en tu compañía, si eres sólo un solitario sin amigos o un grupo de gente con mucho tiempo libre para sus hobbies (como yo!), pueden compartírselo entre ustedes e instalarlo en varias computadoras sin problemas.
Esta versión tiene unas cuantas limitaciones en las funcionalidades más avanzadas, realmente son cosas que no evitarán que hagas un gran juego, así que no les tomes mucha importancia. Al fin y al cabo es una versión gratuita y funciona bien! Por otro lado, si ocupas comprar licencias de cualquier plataforma en la que quieras publicar tus juegos, ya sea Xbox, playstation, etc. Si buscas la opción accesible, PC y WebGL, más adelante te enseñaré a publicar en ellos y obtener buena visibilidad, así que quédate conmigo y te irá bien (jejeje FD).

Si más distracciones, abróchate los cinturones y vamos al tutorial!
Una vez que hayas abierto el programa, escogido un nombre para tu proyecto y se haya cargado una nueva escena, serás obsequiado con una bella vista de la pantalla principal de Unity. No voy a manejar cada minúsculo nombre técnico para cada sección y objeto en Unity, ni yo los sé todos. Pero me basaré en los nombres que se muestran en sus etiquetas y son fácilmente visibles.

Esta pantalla principal se llama el Editor de Unity, hay otra pantalla con la que se puede trabajar, que es el Editor de código, en el caso de Unity, emplea Monodevelop como editor predeterminado.
No me meteré muy a fondo en este tema por ahora, lo guardo para futuros tutoriales, pero sólo como información adicional, te diré que puedes cambiar a cualquier editor que te guste, Visual Studio, Notepad++, lo que sea.
Yo prefiero Monodevelop porque es más práctico, no necesitas instalar programas externos y tiene un bonito corrector de sintaxis que te ayuda a ahorrar tiempo al codificar. Por ahora, olvidémosnos de esto y enfoquémosnos en el Editor de Unity!
En este tutorial aprenderás Unity por medio de ejemplos, en este caso, por petición del público, haremos un simple juego de género disparos (shooter), con una cámara de tercera persona aérea fija y manejando gráficos 2D. Porque esos son más simples de manejar y producir uno mismo.
Si no tienes ganas de producir tus propios assets, yo estaré subiéndolos a mi abusada página de Itch.io, ahí los podrás descargar sin ningún problema.

Por el momento, no compartiré la escena de ejemplo de Unity (estaré haciendo eso cada siguiente tutorial), así te obligo a trabajar y hacerla tu mismo (vamos, no es nada difícil!). Así que esfuérzate y apréndele!
Por ahora, puedes obtener las imágenes para este tutorial y ver el Live Demo aquí…

Checa el Live Demo y descarga los assets aquí…

Live Demo Unity introductory tutorial P.1

Pero como yo creo primero en las bases y luego en la aplicación, te enseñaré un poco sobre diseño de videojuegos básico extraídos de un genial libro llamado Level Up por Scott Roger, te lo recomiendo ampliamente!. Antes de comenzar, necesitas planear cómo será tu juego, los aspectos técnicos ya han sido determinados, veamos qué falta.
Level Up presenta un genial recurso llamado Game Design Document, o GDD para abreviar. Básicamente es la biblia de tu videojuego, contiene toda la información que requieres para que se haga realidad de acuerdo a tu visión, muy útil si estás trabajando con un equipo de personas, o tienes mala memoria o no has decidido todos los aspectos del juego todavía. Te servirá para definirlo completamente, tomando el GDD como guía para dejar que tu imaginación vuele.
El GDD comienza con la portada de tu juego, pero podemos dejar eso para otro momento, pues ni siquiera hemos decidido el resto del juego!
Ponle un nombre a tu juego, esto te ayudará a nombrar el proyecto en Unity también, el mío se llama Unity 3D beginners tutorial, pues eso es lo que es, pero puedes trabajar con lo que quieras, como Rapid Shot o como te plazca.

Lo siguiente será establecer los objetivos del juego, en este caso, algo simple funcionará, como matar a todos los enemigos sin morirte en el proceso!
Decide una historia para unificar los eventos que sucederán en el juego:
Cómo comenzará la historia para tu jugador? Cuáles son las condiciones que desencadenarán los eventos del juego? Esta será la historia que pondrá en movimiento las acciones que el jugador deberá tomar para cumplir con los objetivos del juego. En este caso, será algo simple como que el personaje Gun McShooter sale de su casita, entonces un montón de grosera gentuza violenta aparece alrededor de él, disparándole sin razón y sólo por diversión. Gun, siendo el tipo rudo que es, no se quedará cruzado de brazos para permitir que chusma iracunda le llene de agujeros su sombrero favorito, así que luchará y se llevará de encuentro a cualquiera que le dé problemas. Esto comenzará nuestra historia.

Lo siguiente que necesitas definir son las locaciones contextualizadas a la narrativa. En mi caso, mantendré todo dentro del mismo escenario, algún tipo de pueblito del viejo oeste, con obstáculos, barricadas, ventanas, puertas y otras cosas útiles como fuerte para disparar u ocultarse. Quizá algunos animales que te ayuden u obstaculicen. Todo puede ayudar para modificar las mecánicas de juego.

Finalmente, tenemos el final! Debes decidir si el juego terminará cuando mates a todos, o te acabes todos los niveles, o cualquier objetivo que tú quieras. En este caso, los niveles consistirán en el aumento del grado de dificultad de las mecánicas de juego, más enemigos, más armas para ellos, inclusive más inteligencia artificial. Pero a cambio, el jugador tendrá armas más potentes, más recursos, inclusive más equipamiento y cosas así. Todo terminará después de una cantidad dada de niveles, porque no me interesa hacer un juego de infinito incremento en dificultad.
El resto del GDD habla sobre controles de juego, requerimientos técnicos, mercancía y publicidad, escenas de película (introducción y logotipo), algunas interfaces más, detalles de ambientación, diagrama de flujo del juego (si es que tienes varios niveles e interfaces, lo que este juego no tendrá porque simplemente es una introducción y eso es para niveles más avanzados de dominio en Unity!) y cámaras de juego (por ahora, sólo diremos que es tercera persona y aérea).
Casi todo esto tiene más que ver con tutoriales sobre programación, pues eso es lo que te permitirá añadir esas funciones.
Por ahora, nos conformaremos con lo básico de la estética y organización del juego (pero expandiremos más eso en posteriores tutoriales). Si gustas, puedes ir decidiendo lo demás mientras lo esperas. Si realmente no tienes idea qué quiere decir cada cosa, busca el libro, o espera a que los tutoriales aparezcan! Ahí cubriré todos esos detalles mientras desarrollamos el juego, así que mantente alerta para obtener más contenido!
Ahora que has tomado algunas decisiones básicas para el juego, ya podemos jugar un poco con el Editor de Unity!
Primero, necesitas identificar qué es una escena, que es donde todas las cosas que conforman el juego serán añadidas, colocadas, distribuidas y accesibles desde el juego. Lo que no esté en una escena, no puede ser usado durante el juego, a menos que tengas un script especial que te permita hacerlo.
Piensa en la escena como el nivel de un juego, puedes tener tantas escenas como niveles, a menos que tus niveles sean de incremento en dificultad y se quede igual el transfondo y la utilería empleada en él. O puedes hacer cambios ambientales durante el juego a través de scripts, inclusive quedándote en la misma escena, pero eso es truculento.
Además, cambiar escenas permite que el juego refresque los scripts, las cosas y personajes muertos, perdidos o aparecidos y permite tener mejor orden a tus niveles.
Puedes hacer una escena con una temática del viejo oeste, y otro con temática subacuática. Tener todos los enemigos, NPC, utilería y cualquier otra cosa apropiadamente añadida y acomodada en ambos niveles, cada uno exclusivo para controlar el flujo, el consumo de memoria y sus mecánicas de juego. Y cuando quieras algo nuevo, sólo requerirás cambiar la escena. Tal es el poder de esta forma de organizar niveles!
Tú mismo puedes ver los elementos de la escena en la scene Hierarchy Window…

Y puedes modificar la escena en la Scene Window…

La escena se puede visualizar como se verá durante el juego en la Game Window. Por default, cada uno de ellos viene ya abierto para que los conozcas y tengas un acceso directo a ellos.

Una práctica importante es siempre guarder los cambios que se hagan a una escena, ponerle nombre y almacenarla en una carpeta adecuada, así no se perderá entre otros archivos asset del juego.

Ahora que estamos jugando con las diferentes ventanas en la interface del Editor Unity, hablemos sobre ello! Yo recomiendo que personalices la interface gráfica del Editor Unity, checando esta sección aquí…

Qué es un layout? Simple, es un acomodo predeterminado que puedes escoger para organizer las ventanas del editor en el espacio del mismo. Pero qué son esas ventanas del editor? Toma una mirada aquí…

El menu Window es la lista desplegable que te permite escoger qué ventana abrir. Una ventana es un visor a ciertas propiedades de un cierto GameObject en la escena, ello te permitirá accesar a características especiales clasificadas por el nombre de la ventana. Como la Editor Window, que sirve para editar la escena, o el Hierarchy Window, que permite modificar la jerarquía.
Yo tengo mis propios layouts personalizados (que puedes ver bajo el nombre Mary). Cada una la empleo para potenciar mi flujo de trabajo y lograr una experiencia más eficiente. Originalmente, tu tendrás algo como esto…

Adelante, juega con el layout, puedes arrastrar y soltar las ventanas conforme tu lo quieras. Mi Layout principal (que llamé Mary Code), es el que utilizo cuando estoy comenzando un nuevo proyecto, puedo fácilmente accesar a mis assets (Project Window), editar mi jerarquía (Hierarchy Window) y ambos los acomodo del lado derecho; porque soy diestra y occidental, por tanto, leer contenido de izquierda a derecha es natural para mí. Tengo mi Scene Window a un lado del Game Window, para fácil y rápidamente intercambiar entre una y otra mientras hago la corrida de prueba (play test), además de tenerlas ocupando la mayor cantidad de espacio visual. En el fondo tengo el Inspector Window en modo debug (dale click a las tres pequeñas barras de la ventana y selecciona debug.

Esto te ayudará a ver esas variables de script que no sean accesibles desde el Inspector Window (para que sean accesibles, necesitas etiquetarlas como public en el código, si no, esta es la única forma en que podrás verlas, esto lo manejaremos más adelante).
Lo siguiente es la Console Window, que te mostrará durante el play test qué pasa con los códigos, los bugs, advertencias (cosas que suceden que no están tan bien como deberían estar!) y cualquier otro detalle que le digas al código que te muestre (usando el método debu, que intentaremos después).
Finalmente, la parte más importante para modificar GameObject, la Inspector Window! Aquí podrás ver todas las propiedades de los objetos que tengas en cualquier lugar del Unity Editor, un asset, un GameObject, todo lo que puedas accesar y modificar.

Si lo deseas, cópiate de mi Layout, sé que lo quieres jejeje xD.

Hemos estado hablando mucho de GameObjects, pero qué son!? Son los elementos del juego dentro de Unity que puedes modificar para crear un juego. Piensa en tu personaje jugable o cualquier cosa que quieras dentro de un juego, todo será un GameObject. Las cosas que no serán gameObject son materiales, texturas, videos, códigos y otros recursos externos, todo esto se llama Asset. Tú deberás poner los assets dentro de gameobjects, pero no puedes tenerlos por sí mismos por ahí en tu juego, tendrá que estar añadido a un plano, un cubo, o cualquier otra cosa.
Hablando de suelos, nuestro pequeño juego necesitará un piso donde todo tendrá lugar y pasará! Veamos cómo añadir gameobjects a las escenas! Sólo da click al menú Create sobre la Hierarchy window (ese lugar donde tus gameobjects serán listados conforme los añadas).

Enfoquémonos en un gameobject especial por ahora, el Terrain, selecciónalo y verás esto aparecer en tu escena.

Podrías no saber qué es al principio, se ve tan alien desde esa perspectiva, pero te compartiré un secreto, el Editor Window puede ser navegado! Puedes ver esos controles e la esquina superior?

Si seleccionas el primero (con forma de manita), podrás ver que el apuntador del mouse cambia a una mano, si tu das click en la escena y arrastras por ahí, podrás hacer pan en la vista, de esa manera, podrás ver mejor qué hay ahí!

Para controlar major los alrededores, puedes hacer zoom in o out (adentro o afuera) presionando la tecla Alt y el botón derecho del mouse, y rotar la vista con el botón derecho del mouse solo. Has zoom out hasta que puedas ver la extensión de tu terreno, el mío es enorme porque está configurado así desde un proyecto previo o algo. Puedes ver las medidas reales dando click izquierdo en el Terrain gameobject y checando en el Inspector window.

Puedes ver bajo la resolución los valores que le darán las dimensiones reales del terreno. Si quieres tener tierra vasta para explorar, pon valores altos. Pero ya que estoy tratando de mantener las cosas simples, lo cambiaré a width (anchura) 100, lenght (longitud) 100 y height (altura) 50. Height te permitirá terraformar el plano con los brushes que puedes experimentar tu mismo, formando valles y colinas. Una vez que hagas algún cambio en los primeros dos valores, podrás ver que el terreno cambia sus medidas reales, pero para height sólo notarás sus cambios una vez que edites el terreno.

Ahora que tienes un terreno que consume menos recursos gráficos, hay que editarlo! Puedes ver que hay una sección en el Inspector window etiquetada como terreno, esto se llama Component (componente). Este component es un script que el Inspector puede mostrarte para que modifiques los valores.
Algunos scripts se controlan internamente y no se pueden abrir en el Script Editor para modificarlos, pero otros si, los que están hechos por ti, o alguien más! Aquí lo importante es que puedes abrirlos y modificarlos como tú quieras.
Si le quitas un componente, el gameobject dejará de funcionar como lo que sea que ese componente le permitía hacer. Por ejemplo, si quitas el componente Terrain, ya no será un terreno, sólo un plano aburrido… pero no! Porque ni siquiera tiene ese componente, será solo un gameobject vacío, nada más que una ubicación en el espacio. (útil para otras cosas, pero no como un piso…).
La parte divertida sobre los componentes es que puedes crearlos tú mismo y hacer tus propios gameobjects personalizados! Para aclarar más, esos campos width, height y lenght que modificamos se llaman propiedades, son variables internal de dichos scripts. Cuando hagas tu propio componente (codificando un script), y pongas algunas variables públicas, esas serán tratadas como propiedades y podrán ser accesibles a través del Inspector, qué bello es Unity!
Por ahora, nos concentraremos en esas etiquetas con íconos bajo el componente Tearrain. Esas contienen herramientas para editar el terreno, intentaremos la que tiene el ícono de brush en ella. Te permitirá añadir una textura de terreno para pintar sobre el suelo y hacer que deje de verse tan plano y aburrido.

Primero, necesitarás una tectura en tus assets. Dale click en el menú Create de Project window.

Elige la opción Folder del menú desplegable, dale un nombre como lo que tu quieras usar para identificar lo que contiene (en este caso, textures estará bien). Puedes hacer esto por cada tipo de assets que insertes en el Editor Unity, de esa forma, tendrás un orden adecuado para cada cosa!

Para añadir la textura.png para el terreno, necesitarás minimizar el Editor Unity a un lado y el explorador de archivos al otro y arrastrar el archivo asset a la carpeta debida. Este es el archivo que se puede descargar desde Itch.io! Si aparece una pequeña flecha+ abajo del apuntador mientras arrastras el archivo, quiere decir que lo estás haciendo bien, puedes liberar el botón del mouse para que el archivo sea añadido a la carpeta escogida.

Escoge Edit textures, añade la textura, y en la ventana que se despliega, escoge normal, y añade ahí la textura que cargaste; luego selecciona albedo y repite el proceso. Modifica la repetición (tiling) como te guste, si pones las mismas dimensiones que en witdh y lenght, se extenderá a todo lo ancho y largo del terreno, sin crear un mosaico. Cuando esté listo, da click en Add.

Puedes jugar alrededor del resto de las herramientas, muchas de ellas son auto explicativas, siéntete libre de experimentar a tus anchas, eso te ayudará a aprender! También, puedes añadir tantas texturas como gustes, pintándolas sobre el terreno para tener un campo diverso, diviértete!
Ahora tenemos que acomodar la cámara de acuerdo a lo que habíamos decidido. Por default, Unity siempre coloca una cámara y una luz en las escenas nuevas. Es importante que recuerdes que una escena no puede ser reproducida sin una Main Camera, y cómo sabes que es la main? Tienes que prestar atención a las etiquetas!

Ese es el campo de Tag, que funciona como una etiqueta que le dirá al engine qué cámara es la principal. Puedes tener muchas cámaras con diferentes modos de visualización, ángulos, enfoques, etc. Dentro del mismo juego, que cambien con el click de un botón, simplemente todas tendrán la misma etiqueta y se activarán y desactivarán en turnos.
Además, otras cámaras sin etiqueta Main te pueden ayudar a crear objetos especiales para visualizar diferentes cosas, como tener una pantalla de TV, una videocámara, un espejo, un retrovisor, etc.
Así que cuando sea que coloques una nueva cámara, asegúrate de que sea o no Main, estableciendo el tag apropiado para identificarlo. Presta especial atención al componente AudioListener, todas las cámaras Main deberán tenerlo, pero sólo una activa por escena; de otra forma, tendrás errores con el audio y eso no es para nada bueno!
Hay otras etiquetas para otros propósitos, y además, puedes añadir tus propios tags para lo que ocupes, pero los dejaremos por el momento hasta siguientes tutoriales!

Por ahora, nos enfocaremos en la Main Camera que tenemos que modificar, puedes ver que está desenfocada (en el Game Window), necesitamos apuntarla hacia el terreno, apuntando desde el cielo. Cambiemos eso!

Con la cámara seleccionada, dale click al Segundo ícono donde la manita Pan está, este ícono tiene forma de cruz, va a activar el gizmo de desplazamiento sobre la cámara.

Si das click y arrastras sobre una flechita de color que se despliega, o sobre el cuadradito que se encuentra entre dos o tres de ellas, puedes mover la cámara alrededor en relación al espacio dentro de la escena. Haz zoom, rota o panea la vista para poder ver mejor el terreno y coloca la cámara justo en medio.
La cámara cambiará luego, en relación al personaje jugable, pero se requerirá un script para lograrlo. Por ahora, usaremos la cámara como un visor simple para saber cómo se está viendo la escena conforme colocamos más gameobjects.
Si necesitas ayuda para saber cómo orientar mejor tu vista, aprovecha el giszmo del cubito con los conos coloridos. Si alguna vez has usado algún producto Autodesk, este tiene la misma función que el ViewCube de navegación que usan muchos de sus productos, pruébalo, es divertido!

Por el momento, la cámara está bien donde la dejamos, pero hay un problema!

Por default, Unity pone a la cámara mirando hacia la vista frontal, pero la necesitamos mirando hacia el suelo! Hay que cambiar eso, escoge el ícono con las flechitas en círculo, el gizmo cambiará a algo como una esfera hecha con cuerdas de colores.
Por qué todos esos gizmos tienen los mismos colores? Pues así lo manejan estándar varios programas de modelado 3D, es un código de colores para marcar y distinguir entre sí los 3 ejes de manipulación 3D virtual!
Si no sabes qué color es de qué eje, sólo mira el cubo con el gizmo que tiene conitos en la esquina superior derecha, así es, el viewcube. Necesitamos rotar la cámara 90 grados en el eje z o x, o eso es cómo está indicado en el transform local de la cámara, y eso es todo lo que importa!

SI deseas más control al modificar esas propiedades en cualquier gameobject, puedes referirte a la ventana Inspector. Cualquier gameobject, vacío o no, siempre posee su componente Transform, experimenta cambiarle las propiedades en cualquier campo que gustes, en este ejemplo, ocupas cambiar la propiedad rotación.

Cuando termines con la cámara, será tiempo de añadir al jugador! Así que pongamos nuestras manos en acción con otro gameobject que Unity te da por default. Verás, no hay nada de malo en utilizar los gameobjects predeterminados que incluye Unity, siempre puedes modificarlos acorde a tus necesidades. Conocer cómo conseguir lo que quieres con poco esfuerzo y qué usar en determinado caso diferencia a un pro de un no0b!
Puedes ver aquí que hay una opción créate 3D object. Talvez quieres experimentar con ellos, sólo para saber cómo se siente, talvez bien, quién sabe! … Pero esperen! Estamos haciendo un juego 2D! Sólo debemos usar gameobjects 2D, cierto? Bueno, quizá, quizá no! Cómo se supone que lo sepa!? Oh, cierto, estoy haciendo este tutorial, ejem… Así que veamos…

Los gameobjects 3D ted an más opciones y posibilidades, lo que siempre es Bueno! Qué necesitas? Qué puedes usar? Bien, para comenzar, ocupas un gameobject personaje. Cómo funciona eso? Ocupas algo que pueda moverse por ahí, sostener armas, disparar y esconderse detrás de objetos, así como ser afectado por ataques enemigos y no atravesar el suelo o los obstáculos!
Uh? Qué dije acerca de ir a través del suelo? Así es! Basicamente eres un fantasma aquí! Cuando el juego comienza, si tienes masa, irás a través del suelo, a menos que tengas colisión también. Pero de qué estoy hablando? Tú eres sólo un bebé en entrenamiento y no haz tocado un libro de física en tu vida! Jajaja, es broma!=P (no me mates! Aún sirvo xD)
Bien, recuerdas esos aburridos conceptos de masa, gravedad, impenetrabilidad y todo eso que tanto dolor de cabeza te causó en la escuela? Todos ellos aplican aquí, así que si tienes una comprensión básica de ello, qué bien! Yo me las arreglo solamente con un conce´to vago de todo ello. Podría ser óptimo conocer sobre ecuaciones y demás, pero Unity puede hacer un montón de esas cosas por ti, a menos que ocupes algo más avanzado, entonces estarás en problemas!
Dado que apenas estás comenzando aquí, no necesitas preocuparte aún, pero nunca es tarde para aprender cosillas extra, si te llama la atención, ve y refresca tu memoria! Mientras, veamos qué son esas cosillas gameobject 2D Sprite, escógelo y explóralo con el Inspector.

Por ahora, tu sprite es invisible, no tiene una textura, y puedes ver que sólo tiene dos componentes, Transform y Sprite Renderer. Sprite Renderer no tiene masa, ni colisión, no será afectado por gravedad, es básicamente aire! Este gameobject Sprite sólo sirve como un contenedor para texturas 2D, pero efectivo para un juego 2D! Así que pongámosle la textura de personaje que te doy con los assets, y añádelo al proyecto, luego al sprite renderer…

Ahá! Has descubierto que no se puede añadir al Sprite Renderer! Te da un círculo negro bloqueado, cierto? Te engañé! Primero necesitarás dar click en la textura, y en el campo desplegable Texture, puedes encontrar el tipo Sprite (2D and UI), cierto? Dale click, lo necesitarás.

No necesitas cambiar más que eso (más adelante, con animaciones, veremos otras opciones), sólo dale click en el botón Apply al mero fondo del Inspector, y estarás listo para continuar!

Ahora, la textura tiene una pequeña flechita desplegable y dentro, otra cosita cuadrada llamada igual, este es el sprite dentro de la textura que Unity ha identificado. Si tienes múltiples sprites en una imagen (como un sprite sheet para animación), puedes dividirlo con el Sprite Editor (dentro de las opciones que no ocupas modificar por ahora), y serán enlistadas aquí para que las veas y hacer cambios o manipularlas conforme ocupes.
Por ahora, sólo ocupamos esta imagen solitaria, no haremos más cambios en el personaje hasta que sea tiempo de aprender animación con Mecanim. Qué es eso, y con qué se come!? Bien, así es como se llama el nuevo sistema de Unity que controla la animación.
Es un sistema de codificación gráfico con nodos, simple de usar y comprender. De verdad! Prácticamente lo aprendí por mi misma, después de una serie de migrañas mientras me figuraba qué hace que!
Como sea, de vuelta al tema, ahora ya podemos poner el sprite en el juego! Arrastra y colócalo en el Sprite Renderer y ya está! Ahora intenta rotar la vista para darte cuenta que sólo es una imagen plana que se repite atrás y adelante, perfecta para un juego 2D, con poco consumo de recursos y todo.

Bueno, pero ahora te darás cuenta que la perspectiva de la imagen está equivocada, oh no! Hice el sprite mal! No, espera! No me culpes, es tu culpa! Así es, no has cambiado la cámara aún. Es una cámara aérea, pero no necesariamente de arriba abajo. Yo odio esas cámaras, cuál es el chiste de ver todo desde arriba?

Qué hay de divertido en usar esa perspectiva? Sólo parece un hotcake con algunos tumores en su cabeza y una banana sujetando una salchicha. No se entiende, qué horror! Y mi personaje tan bonito que estaba, lloro lágrimas de sangre! T.T

Bien, si te gusta esa vista, entonces cambia los sprites para que se vean bien, es tu decisión. Lo importante aquí es que sepas cómo quieres que sea tu juego y te apegues a ello. Por mi parte, ya cambié la cámara, así que no te preocupes ;D.

Lo Bueno es que el personaje fue creado en el mismo lugar que la cámara, pues la tenía seleccionada cuando añadí el 2D sprite. Si tu personaje está en otro lado que nada qué ver, dale click en el pequeño engranaje a un lado del componente transform de la cámara, entonces selecciona Copy Component, luego dale click al engranaje del transform del personaje y selecciona Paste Component Values. Automáticamente los dos se fusionarán en el mismo lugar, qué útil!
Así mismo, puedes usar esta misma técnica para copiar y pegar el mismo componente a un nuevo gameobject que no lo tiene, y a la vez ocupas que tenga los mismos valores, o puedes cambiarlos después. Recuerda este pequeño truco en el futuro!

Justo ahora, el personaje no tiene físicas y no se puede mover, la cámara no lo seguirá tampoco, todo son sólo objetos torpes, esto no es un juego… ni siquiera es divertido y ya me aburrí, adiós!!…. Ups, este es mi tutorial, estoy aquí, soy profesional, lo prometo!
Bueno, podemos dejarlo así por ahora, pero te llevaré un nivel más arriba (como el libro, woah!). Vamos a añadir un control de físicas al personaje, que le permitirá moverse, interactuar con otros, tener amigos, amores perdidos y cualquier otra loca aventura! Escoge un 3D gameobject Capsule, mientras tienes seleccionado con doble click el gameobject del personaje.

Si lo hiciste bien, se añadirá en la misma posición que el personaje (si no, intenta de nuevo, o copia las coordenadas), también, tiene volumen y color, es real! Inclusive me preocupé en etiquetarlo apropiadamente. No más ítems visibles, yupi! Pero malas noticias, no necesitamos que sea visible!

Para arreglar este problema, ve al component Mesh Renderer de la cápsula y dale click al pequeño cuadro azul marcado, desmárcalo y observa cómo desaparece del mundo virtual!
Podrás estarte preguntando, otro renderer, qué raro, qué es un renderer! Tengo miedo, hay muchos términos nuevos!… Bueno, deja de enroscarte como gusano en el suelo y enfrenta los hechos! Los Renderers permitirán que tus gameobjects puedan visualizarse, renderizarse en el mundo virtual.
Hay más renderers por ahí, como el Skinned Mesh Renderer, que permite que un modelo 3D importado a Unity pueda visualizarse, pero eso es muy avanzado, y también, pertenece a un mágico juego 3D o que tenga gráficos 3D involucrados. No te preocupes, talvez podamos usar objetos 3D para simular un mundo 2D!
Tú sabes, incluso cuando emules un mundo 2D, hay veces que ciertos objetos necesitan ser 3D para poder visualizarse correctamente en todos los ángulos. Dado que nuestra cámara estará fija, que significa, no rotará alrededor del mundo (más que cuando el personaje se mueva) o del personaje, sólo lo seguirá por detrás; tener cualquier cosa aparte de un personaje 2D es super exagerado, ni siquiera mirará la cámara!
Y dado que este es un juego 2D, si quieres escenas de película con el personaje viendo la cámara, (llegaremos a tenerlo en futuros tutoriales!), sólo bastará con que añadas las animaciones y las reproduzcas en pantallas de tv. No ocupas más, y te ahorra el problema de tener que hacer más gráficos para el personaje (soy floja, y qué?).
Dado que este es un simple juego para tutorial, eso se permite, pues lo importante es que aprendas a usar el programa y lo básico de programación y diseño de juegos, no que hagas el siguiente Final Fantasy xD. Pero para tus propios juegos avanzados, siéntete libre de experimentar lo que quieras!
De vuelta al tema, ahora que tenemos nuestro cuerpo físico del personaje, no necesitas mover más desde donde está, sólo ubícalo en la mitad del personaje. Luego experimentaremos más con esto.
Puedes ver que este capsule gameobject tiene ya un componente llamado Capsule Collider, como con los Renderers, hay muchos Colliders en Unity, con diferentes formas (inclusive Mesh Collider perfecto para el Skinned Mesh Renderer!).
No tocaremos más por ahora, pues se explicarán después. Sólo recuerda que esto le permitirá al personaje interactuar con lo que sea que tenga otro Collider, cool, no crees?

Justo ahora, este Capsul gameobject no es parte del personaje, cuando uno se mueva, el otro no lo seguirá, porque no están conectados, qué sucede? Si observas nuestra Hierarchy Window, están en lugares diferentes. Qué tiene eso que ver con todo? Bien, en Unity las cosas deben estar emparentadas para poder funcionar juntas, o algo similar, todo depende del contexto.
Para arreglar esto, arrastra y deposita el Character Control (Capsule gameobject) dentro del sprite del personaje, y ya está, ahora el Character Control es hijo del carácter sprite que es su nuevo papi. Intenta mover el sprite y verás qué sucede! Aprovecha y emparenta la cámara al sprite, de esa forma, no tendrás que ponerle un script para que le siga por donde vaya el personaje, lo hará en automático!

Otra cosilla extra que quiero enseñarte es sobre la cámara, puedes jugar con el menú desplegable debajo del componente Camera (que lo convierte en cámara, duh). Existe la opción de vista en perspectiva y ortogonal. Escoge lo que te guste, entonces arrastra o escribe la profundidad de campo (slider perspectiva) o tamaño (campo ortogonal), que te guste.
Experimenta con las opciones, intenta modificar y agregar cosas, aprende explorando!

Si tienes cualquier pregunta, no dudes e preguntarme por aquí o en la página de Facebook. Diviértete y adelante, añade más gameobjects con diferentes formas, crea tus propios ítems de utilería y colocalos alrededor del campo. Puedes usar cualquier imagen que encuentres en internet, cualquier cosa plana funcionará.
En la próxima lección, nos meteremos a aprender programación para mover al personaje alrededor, esencial en cualquier juego, a menos que sea una novela gráfica…
Un tip final, si das click en la pequeña flechita de arriba al centro, entrarás en el modo Play Test, justo ahora no hay algo que jugar, pero puedes experimentar con ello. No olvides guardar el proyecto!

Unity introductory tutorial P.1

Hello my friends! This tutorial was requested by a cool foreigner follower in the facebook page! He wanted to learn Unity with something written and clear english.

I emphatize with him, because the video tutorials tend to be difficult to understand, specially for non native english speakers like us; also, it´s weird trying to pause the video each time to know what to do and if there is code involved, is frustrating trying to see what it´s written in small letters!
So here we are, with this comprehensive serial tutorial I´m going to be publishing each week or so.

I can´t assure a regular basis (unless a legion of followers ask me to do so gifting me with lots of likes and shares!), but here you have the first part, and this will give you a whole understanding of the Unity editor, for setting up your scene.

The next tutorials will be about codification, I will have to indulge myself in nasty stuff like the basics of c# and Unity API, so that you can learn to code from 0 previous experience!
You just need the game engine Unity 3D 5x installed on your computer. In my case, I have 5.5.0f3, because from there on the WebGL is more optimized than in previous versions, go ahead and download whatever you may want.

You need to make an account to download it and install it, once you do that, you can install it in whichever computer you may want. You can even install it in various computers simultaneously, I have never had problems with that.
So go ahead and create your little indie company with friends and such, or whatever you like, if you don´t have more than certain amount of people working for you, and you don´t earn more than certain amount of money, you won´t need more than the Unity personal edition.

This is also true if you don´t need the advanced functionalities of the engine, I don´t use them, and don´t have any plans on them yet, so if you are the same, stay with the free version, otherwise, serve yourself with a paid version.

Without further addo, Let´s begin the tutorial!!

Here we have the main screen of unity, i will save you the mindbogging task of memorizing the technical names of each section of the unity interface, I don´t even remember all of them, I will just name them like I know them, by the name showed in their labels.

This is called the Unity Editor, there is another screen you can be working with, called the code editor, if you have previous experience with that, you may know there are lots and lots of code editors out there, but Unity comes with its very own integrated editor, the Monodevelop.
I won´t indulge too much on this topic, because it will be explored in next tutorials, but just so you know, you can change the predetermined code editor to whatever you may like, visual studio, notepad++, whatever.
I keep mine as monodevelop, its more practical (I don´t have to install third parties) and it comes with integrated sintax corrector, that´s useful to save you time editing code. So let´s forget about this until next time, and focus more on the Unity Editor!

So we are going to learn Unity by example, in this case, by the request of the public, we are going to make a simple but cool shooter genre videogame, with a third person fixed aereal camera and 2d graphics, because those are easier to manage and produce by yourself. ´
If you don´t feel like making your own assets (you lazy non artist… kidding!Hahaha), I uploaded the simple but usable assets I use on this tutorials in my Itch.io page.

I won´t be sharing the Unity example scene as of yet (until the next tutorial!), because I explain how to set it on this tutorial, so make the effort to make it for youself.
For now, you can get the images I made for this, just follow this links…

Go play the live Demo and download the assets here…

Live Demo Unity introductory tutorial P.1

First of all, you need to plan out your videogame, I already set the technical propierties of it. I´m going to include in this tutorial some basics of game design, on a cool book called Level Up by Scott Roger, I strongly recommend you to check it out, specially if you just begin with your videogame making career.

Level Up presents you with this cool concept of the Game Design Document, or GDD for short, basically is the bible of your very own videogame, it has all the information you may need to make it real and true to your vision, very useful if you are working on a team, or have bad memory, or haven´t decided all the aspect of the game yet. To flesh it out completely, you can take this as a guide and release your imagination.

The GDD begins with the cover of your game, but we can leave that out for now, because we haven´t yet decided the rest of the game, LOL.
Name your game, this will help you to name your Unity project too, I called mine Unity 3D beginners tutorial, because that´s what it is, but you can work with whatever you like, like rapid shot or whatever.

Next, establish the objectives of the game, in this case, something simple will work, like shooting down all the enemies without dying in the way!

A quick story overview can help:
-the setup, how do your player will begin the game, what are the conditions that will trigger the game, the story that will put into motion the actions the player must take to accomplish the game objective, in this case, it will be something simple like the character Gun McShooter goes outof his house, then violent people start appearing around, gunning for his head for no apparent reason. He, being the badass he is, won´t stand around allowing others to shot him down, he will fight back, thus beginning our story!

Next up, you need some narrative contextual locations, in my case, I will keep everything in the same scenario, some kind of old western town, with some obstacles, barricades, windows, doors to shoot from and maybe some prop animals. Everything can come into play as props and modify the game mechanics.

Finally, we have the final! Decide whether the game ends with you killing everyone or beating all the levels, you can finish with whatever objective you may wish, in this case, the levels will be the augmentation of gameplay difficulty, more enemies, more weapons to them, and even could be more Artificial Inteligence, but in exchange, the player will have more potent weapons, more resources, even equipment and stuff. It will end after certain levels, because I´m not aiming for an endless increasing difficulty level, so that´s it.

The rest of the GDD talks about game controls, technical requirements, some front end for the game (merchanidizing and stuff), opening cutscene (the introductory information and logo splashscreen), some other little interface and ambientation details, game flowchart (in case you have various level scenes and interfaces, which this simple game won´t have because it´s just an introductory tutorial, that´s way too advanced!), game cameras (which, for now, we will just say is third person and aereal).
Almost all this stuff pertains more to the next tutorials on scripting, because that´s what will allows you to add those functions.

For now, we will settle just with the aesthetics and layout of the scene, but you can begin deciding those stuff in the meanwhile. if you don´t know what those mean, you can search for the book if you wish, or wait untill the next tutorials are up, they will cover all that on details while developing it for the game, so stay tuned and like me for more content!
Now that you have taken some basic decisions for the game, we can play around with the Unity editor, let´s do it!

First of all, you need to identify what´s a Unity Scene and what not, a Scene is where all the things conforming the game will be added, placed, distributed and accesible from your game. Whatever isn´t on a scene, can´t be used during gameplay, unless you have a special script that allows you to do so.
Think of a scene as the level of the game, you can have as many scenes as levels, unless your levels are those of increasing difficulty and stay the same in terms of background, props, etc. Or you can change enviromental stuff during gameplay through scripts, and even though stay on the same scene, but that´s more tricky to do.
Also, changing scenes allows the game to refresh the scripts, the broken, missing or death things on the game (like enemies, props, etc.) and more order for your levels.
You can set a scene with a western thematic, and other with a subaquatic thematic, have all the enemies, NPCs, props and stuff properly added to both, each one exclusive of them, control the flow, the memory consumption and the gameplay for them, and when you want something new, just change scene. Such is the power of this system.
You can see the scene elements in the scene Hierarchy Window…

You can modify the scene in the Scene Window…

And you can see how the scene is setup in the Game Window. By default, each of them comes open up for you to easy access them.

An important detail is to always save the changes you make to a scene, name it and store it in a proper carpet so it won´t get lost among the other asset files of your game.

Now that we are playing with the different windows on the Unity Editor Interface, let´s talk about it. I strongly recommend you to customize the graphical interface of the Unity Editor by checking out this section here…

Which is the layout selector? What is layout? You may ask. Well, simple enough, you can change the way editor windows are placed around the way. But what are those editor windows I´m blabbing about? Well, take a look at this other menu…

The window menu, which is the displayable list that allows you to chose which window to open, a window is a visor to certain propierties of a given Game Object on the scene, it will allow you special features classified by the designated name.
I have my own custom layouts (you can see them by the name Mary, LOL!), each one I use to potenciate my workflow to a more eficient experience. For now, you may have something like this…

go ahead and play around with the layout, you can drag and drop windows as you please. My main layout (called Mary Code), is the one i use when I´m beginning a new project, I can easily access my assets (project window), edit my hierarchy, both at the right side, because I´m right-handed and occidental, so watching content from left to right is natural for me. I have my scene besides the game window, so that I can switch between the two during play test and have them ocuppying the most available space (great for visualization). In the bottom I have debug mode Inspector (click on the little three bars of the window and select debug).

This will help you see those script variables not accesible from inspector (you have to label them public for them to be accesible, otherwise, this is the only way you can see them).
Some things need to be hidden so some dummy artist playing around with the scene and gameobjects won´t break your delicatetly measured codes and such, others are internally modified by the code and you won´t need or have to modify them, but is important visualize them so you can know what´s happening during gameplay.

Next is the console window, it shows you after each play test what happens with the codes, the bugs, the advertencies (something that is not as right as it should be!) and some other thing you tell the code to show for you (with the method debug, we will see some of it later!).
Finally, we have the most important part for modifying gameobjects! The Inspector window, here you can see all the propierties of the objects you have in whatever place of the Unity Editor, an asset, a gameobject, everything you can access and modify.

If you want to, just go ahead and copy me, I now you want to xD

Next one, you have to be familiar with GameObjects, which are the game elements inside Unity so that you can edit them and make a game, just think of your playable character or whatever else you may want inside a game, everything will be a GameObject. The things that will not be GameObjects are materials, textures, videos, codes and external resources, called assets, which you will put inside the game objects, but you can´t have by itself a texture around your game, it will have to be attached to a plane, a cube or something.
Our little game will need a nifty floor where everything will take place! Let´s see how to add GameObjects to the scenes. Just click on the Create menu over the scene hierarchy (that place where your GameObjects will be listed after you add them).

Let´s focus on a special GameObject for now, the Terrain, select it and you will see this in your scene…

You may not know what it is at first, it looks so alien from that perspective, but let me share you a secret, the Unity Editor can be navigated. Can you see those controls in the left superior corner?

If you select the first one (shaped like a hand), you will see the mouse pointer change to a hand, if you click and drag across the editor you can pan the view, that way, you will see more of what is in there!

For more control around, you can zoom in or out by pressing down Alt and the right button mouse, and rotate the view with the right button mouse alone. Zoom out until you can see the extension of your terrain, mine is enormous because of a previous project or something, you can see the real measures by left clicking on the Terrain GameObject and checking on the inspector window.

You can see under resolution the values that will give the real dimensions to your terrain. If you are planning for a game with a vast land to explore, put some higher values here, but because I want to keep things simple, I will change it to something like width 100, lenght 100 and height 50, height will allow you to terraform it with the brushes we are going to use next, forming valleys and cliffs. Once you make some changes on the first two values, you will see the terrain changing its real dimensions, but for height, only once you edit the terrain changes will be noticeable.

Now that you have a less resource consuming terrain, let´s edit it! You can see here there are a section labelled as terrain, this is called a component. This component thingy is an script the Inspector Window can show you so you can modify it.
Some scripts are internally controlled and you can´t open them on the Script Editor to modify them, some others were made by you! or someone else, but the important thing is that you can open them and modify whatever you want.

If you take off a component, the gameobject will cease to function in whatever that component allowed it to do. For example, take off terrain component and it would no longer be a terrain, it will be just a plain boring plane, but no, because it doesn´t have that component, it will be an empty gameobject, nothing but an ubication on the space (which is useful for other things, but not as a floor!).

The funny thing about components is that you can create them yourself and make your own custom gameobjects! Also, those width, height and lenght fields we modified are called propierties, they are internal variables of those scripts, if you make your own component (codifying a script), and put some public variables, those will be treated as propierties and can be accesible through the Inspector, that´s so beautiful!

So, for now, we will concentrate on the little labels with icons under terrain component. Those contain tools for editing the terrain, try out the one with the brush on it. This will allows you to add a terrain texture to paint over the floor and make it stop being so whitey!

First, you need a texture on your assets. Let´s click on the create menu of the Project window.

Chose the folder option from the displayable menu, name the folder as whatever you can use to identify what it contains (in this case, textures is fine). You can do this for every type of assets you insert into the editor, this way, you can have them properly ordered!

And add by drag and drop (over the folder, you have to minimize somewhat the Unity editor to do se) the terrain texture.png I include in the assets folders you must have downloaded from Itch.io! If you have a little +arrow below the pointer while doing this, you are doing it correctly and when you release the mouse button, the archive will be added to the chosen folder.

Chose Edit textures, then add texture, and in the displayed window, chose normal and select the texture you uploaded, then select Albedo and chose the same. Modify the tiling as you wish (if you put the dimensions of width and lenght, it will extend all over the terrain without making a tiled floor) and then click Add.

You can play around the rest of the tools, most of them are self explaining, I will leave them for now for simplicity, but feel free to experiment, it will help you learn! Also, you can add as many textures as you may want, paint them over the terrain and have a diverse field, have fun!

Now, we have to set up the camera so it is as we wish it to be, by default, Unity always places a helpful main camera on newly created scenes. You see, a scene can´t be played without a main camera, how do you know it is main? You may want to look closely here…

That little Tag field works as a label to identify gameobjects from others. Some internal Unity scripts (predetermined components) need them to work properly. By default, the engine always checks on the MainCamera Tag for a camera that will help the player visualize the scene.

Through scripting you can change which camera is the main (thus having many cameras with different modes, like and overhead camera, a third person camera, first person, rotational camera, etc., in the same game, changeable with the click of a button!).

Also, other non-main cameras can help you set special objects for visualizing different things! (like having a TV screen, a videocamera, a mirror, retrovisor, etc.).

So whenever you set a new camera, be sure if it´s main or not and stablish the proper tag to identify it, and also, check for duplicated AudioListeners components, all main cameras should have it, but just one per scene or there will be errors with the audio, and you don´t want that!

There are other tags for other purposes, you can even add new tags for your own purposes, but let´s leave them for some other time!

For now, we can see our Main Camera is off objective, we need it pointing towards the terrain from the sky, so let´s change that!

With the camera selected, click on the second icon where the pan (hand) icon was, the one with the cross shape, this will activate the displacement gizmo on the camera.

If you click and drag one (or a combination of them by their middle square controls) of the three available colored arrows, you can move the camera around in relation to the scene space, zoom out, rotate, pan or whatever you need in order to achieve a better view of the terrain, and place the camera just in the middle of this floor.
It will be changed later, in relation to the playable character, but you will need a script to do so. For now, we will use it as an easy visor to know how the scene is looking up as we place the other stuff on it.

If you need help in settinf up your view with the pan, zoom or rotation tools, just use the gizmo with colored cones and a little cube in the middle. If you have ever used any Autodesk product, this have the same function as the navigation viewcube, try it out, it´s funny!

So now, we are where we want the camera to be, but there´s a problem.

By default, Unity always places the camera facing towards the front view, but we want it to be facing towards the top view! Let´s change that, chose the next icon with the circle arrows. The gizmo will change to something like a sphere, made with colored strings.

Why all these gizmos have the same three colors!? That´s like, so weird, isn´t? No! It´s the standard (or something like that) color code for the three dimensional axis in a threedimensional virtual world (many 3d modelling softwares have it look around and find them all!).

If you don´t know which color does what, just look at the cube with the cones gizmo in the right top corner. We need to rotate the camera 90 degrees in the z or x axis, or at least, that´s what´s labeled in the local transform of the camera, which is all that matters!

If you want more control while modifying one of those propierties of any given gameobject, you can refer to the Inspector window, any gameobject must always have a Transform component, try to change the propierties in whatever field you may want, for this, you need to change the rotation propierty, whatever can work, just experiment around…

When you finish setting up the camera, you can now add the player!
Let´s get our hands dirty with the other gameobjects Unity gives you by default.
There´s nothing bad with using the default gameobject Unity comes with, you can always modify them to your needs, knowing how differentiates a pro from a no0b! Also, knowing what to use in which case.

You can see here there´s a create 3D object option. Maybe you want to experiment with these, just to know how does it feel, maybe nice! Who knows?…. But wait!!!! we are making a 2D game!! We have to use only 2D gameobjects, right? Well, maybe, maybe not! How am I supposed to know? Oh, right, I´m making this tutorial..
So let´s see….

3D gameobjects gives you more options and possibilities, which is always nice! What do you need? What can you use? Well, for instance, you need a character gameobject. How does it works? You need something that can move around, hold guns, shot and hide behind objects, also be affected by enemy attacks and not go through the floor!

Uh? What did I say about going through the floor? Yeah, you are basically a ghost here, when the game begins, if you have mass, you will go through the floor, unless you have collision too. But what am I talking about, you may ask? You are just a beginner baby and haven´t touched a physics book in your life!! Hahaha, kidding.

Well, you know that physic concepts mass, gravity, impenetrability and such? All of them apply here, so if you have basic understanding of it, good, I go through with just a vague concept of it all, the optimum would be for you to know equations and stuff, but Unity can do a lot of those for you…. unless you need something advanced!

But since we are just beginning here, you needn´t worry yet!
So let´s see what those sprite thingies are, chose it and explore it with the Inspector…

For now, your sprite is invisible, it doesn´t have a texture, and you can see it only has a transform and sprite renderer components. Sprite renderer doesn´t have mass, nor collision, it won´t be affected by gravity either, because it´s basically air! This sprite gameobject will only serve as a container for a 2D gameobject! Funny, but efective for a 2D game. Let´s chose our character sprite and add it to the project, then to the sprite renderer…

Aha! You have discovered it can´t be added to the sprite renderer!! It gives you a black blocked circle, right? I fooled you, you first need to click on the texture, there, on the texture type dialogue, you can see the Sprite (2D and UI) type, right? Click on it, you will need it!

You don´t need to change more than that, just click on the Apply button at the bottom of the Inspector and you are good to go!

Now the sprite has a little displayable arrow and inside it, a square thingy named like itself. This is good, if you have multiple sprites on one image (like a sprite sheet for animation), you can split them up with the sprite editor (inside the same options I told you not to change!) and they will be listed here for you to see how they split and if you need to make changes.

For now, we just need this one image, we are not going to make more changes on the character until is time to learn animation on Mecanim. What´s Mecanim? Well, that´s how Unity called its new animation system (the most recent, at least, it has some time now…), yep, they are weird like that!
But it´s a cool graphic codification animation system, easy to use and understand, really, I practically learned it by myself (after getting many headaches figuring out which is what and how does whatever!).

So, back on topic, we have just put our nifty sprite on the game! Yey, now drag and drop it on yur sprite renderer and you are good to go!
Now try rotating around it, you will notice it is just a planar image, perfect for a 2D game with little resource consumption and such.

Well, but you can see the perspective is wrong, I did the sprite wrong, I do know nothing about perspective, me sucks T.T… no, wait!! Don´t blame this on me! It´s your fault, yeah, you haven´t changed the camera yet. I said It was going to be an aereal camera, I didn´t say it was top-down, I hate those things, really. What´s the deal with just having a blob going around with the typical design overhead?

What´s so funny about that perspective!? It just looks like a hotcake with some bulbs on its head and a banana holding a sausage! I don´t know what that is. It´s a shame, my character was so beautifully designed, I´m crying tears of blood right now! T.T

Well, if you like that view, then change it to whatever you like better, it´s your decision, the important thing for you is to know how you want your game to be and stick with it.
And as for me, I already changed the camera, so don´t worry for me.

The good thing here is that the character was created in the same spot as the camera (if you had it selected when you clicked on create 2D gameobject sprite).
If your character is off, just click on the little cog under the transform of the camera, select copy component, then click the transform of the character and select paste component values, and automatically the two will merge in the same spot, that’s useful.
You can even use this to add the same component to a gameobject that don´t have it, but you need it to have the same values too. Remember this little trick in the future!

Right now, the character doesn´t have physics and can´t move, the camera won´t follow the character either, everything are dumb objects, this is not a game, it´s not even funny and I´m already bored, consider me out of this… Ups, this is my tutorial, I´m here, I promise.

Well, we can leave it for now as it is, but I will take you one level up (as the book! woah). Let´s add the physics control to the character, it will allow us to move it, interact with others, have friends, long lost loves and many other wacky adventures! Chose a capsule 3D gameobject while having selected the character…

It will add itself in the same position as the character (if it doesn´t work, delete the capsule, double click the character while in the scene window and try again), but also, it will have volume and color, it is real! I even took the care to tag and name it properly. No more invisible items, yey! But bad news, we don´t need it to be visible…

So, to fix this problem, go to the Mesh Renderer component of this gameobject and click on the little checked blue square, uncheck it and watch it disappear from the virtual world!
You may be wondering, another renderer, that´s weird, what´s a renderer! I´m so overwhelmed by all these new terms! Well, stop curling like a twerp in the corner, the renderers allows you gameobject to be visualized, renderize is to draw in the virtual world~

There are more renderers out there, like the skinned mesh renderer, which allows an exported 3D model to be drawn and all, but that´s way advanced now, and also, it belongs to a 3D game or one with 3D graphics involved. But don´t worry, maybe we can use 3D objects to simulate a 2D world.

You know, even when emulating a 2D world, there are times when stuff around needs to be 3D in order to be seen correctly from all angles. Since our camera will be fixed, which means, won´t rotate around the world or the character, just follow hi around from behind, having anything else besides a 2D character sprite is overkill, he won´t ever be facing at the camera.

And since this is a 2D game, if you want to have cutscenes with him facing at the camera (we can have them, but in later tutorials!), just add them as animations and reproduce them on tv screens, that´s all you need, and it saves you having to make more graphics for the characters.

In this simple tutorial game that´s allowed, because the flesh and the bones are how to use the program and basics of programation, not making the next final fantasy. But for your own advanced games, feel free to experiment with whatever you may want!

Well, now we have a physical body for our little character, you don´t need to move it from where it is, just in the middle of the character is fine. Later on we will experiment with this.
You can see it already has some shady thing called Capsule Collider, as the renderers, there are quite a lot of colliders out there, with different shapes (even a Mesh Collider perfect for its use with the skinned mesh renderer).
We won´t touch them now, and I will explain more about them later. Just know this will allow the character to interact with whatever else has a collider, cool, isn´t it?

But right now, it is not part of the character, so when we make it work with script, they will not be connected at all! Why is that? If you look at our Hierarchy Window, they are in two different places. What does that have to do with anything? Well, in Unity, things must be parented in order to work together or something like that, it all depends on the context. To fix it, drag and drop the character control over the character sprite, and that´s all, now character control is a child to the parent that is character sprite! Try moving around the sprite and see what happens! I went ahead and also parented the camera to the sprite, because that way, you won´t have to script it following the character around, it will follow wherever the sprite goes!

Another extra thing I want to teach you is about the camera, you can play around with the displayable menu under the camera component (which makes it be a camera, after all). There are perspective and orthogonal view type, chose whatever you please, then drag or type whatever field of view (perspective slider) or size (orthogonal field) you want.

Experiment around, try everything and learn by exploring!

If you have any question, don´t think twice to ask me here or through the facebook page. Have fun and go ahead and add more gameobjects with different shapes, or create your own props and place them around the field. You can use whatever image you find on internet, everything is flat, after all, just what you need!

Next time, we can get around making the character moving around, the essencial of any game, don´t you think? Or else, with what will you be able to play? Moving the terrain! Hahaha
One final tip, if you click on the little play arrow at the top of the editor, you can enter test play mode, right now there is nothing to play, but you can experiment with it. Don´t forget to save your project!

Live Demo Unity introductory tutorial P.1



Continue reading Live Demo Unity introductory tutorial P.1

Live Demo NavMesh OverWorld Map System


Continue reading Live Demo NavMesh OverWorld Map System