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

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

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

Unity introductory tutorial P.1

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

Check the Live Demo here…

Live Demo Unity introductory tutorial P.2.1

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

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

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

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

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

Clickable object system for Unity 3D

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

¡Unity 3D introductory tutorial Part 1…

Unity introductory tutorial P.1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Published by

Mary D Kidd

Una misteriosa creativa dispuesta a dejar sus ideas salir y tomar control del mundo. Preparada siempre para innovar ;D

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Your email address will not be published. Required fields are marked *