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!

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!

Metrics

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!

That’s what I’m talking about, I want some action and trials to overcome!

Unity 3D

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…

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!!

Extra details, extra movements, music!

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.

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!

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!

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!

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!

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!

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!

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…

Name it lol ja and Unity will fuck with you and create a new word for the world to see…

Unity 3D

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?

By the way, this is called a block of code, everything between the {} will be used as the instructions of a given function.

Unity 3D

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!

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)

Game controls

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.

Code Variables

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.

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…

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…

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!

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!

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).

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

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!

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!

Metrics

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!

That’s what I’m talking about, I want some action and trials to overcome!

Unity 3D

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…

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!!

Extra details, extra movements, music!

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.

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!

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!

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.

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…

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…

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.

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).

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!

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!

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!

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!

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.

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!