IMPORTANT UPDATE

I have created a more complete and simple to use solution, it is a Unity package to download and import, with a prefab that when dragged into the Canvas automatically produces the fade effect, you can customize several parameters in the inspector. You can download the Unity Package in the link below:

In the following video we see the FADE IN/OUT effect for Unity

New Fade IN/OUT solution for Unity here!

OLD ARTICLE BELOW

Introduction

In this article we’re going to see a simple way to darken the screen in Unity using an image component. This can be very useful for example to use as a transition in a scene change.

In the video below I explain how to use it, but I do not explain how it works, if you are interested in knowing about programming level operation continue reading this article.

🟢 Fade In – Fade Out Effect for Unity

Download Unity Package and Import

Download GameController and UIManager scripts.

Step-by-step solution

Elements of the hierarchy

We will create all the elements necessary to solve the problem. First an empty GameObject that we will call “GameController” and a GameObject type Canvas that is the one that will contain all the elements of the graphical interface.

Fig. 1: We start by creating an Empty GameObject with the name “GameController”.

Fig. 2: We created Canvas to show graphical interface elements.

In figure 3 we see these elements created and placed at the beginning of the hierarchy.

Fig. 3: I give the Canvas the name “UI” and place the control object and the canvas in the first position.

Image to dim the screen

The next thing we do is create an Image as a child of GameObject UI. This image will be used to block the vision of the camera.

Fig. 4: Right-click on the UI object to create an image.

In the inspector in the image component we make the color black.

configuration of the color for an object image in unity
Fig. 5: We make the color of the image black.

Canvas Scaler Setup

Let’s go to the GameObject UI and in the inspector, in the component CanvasScaler we select the mode “Scale with screen size” in the field “UI Scale Mode” (figure 6). With this we can make the elements of the graphical interface modify their size according to the size of the screen.

Fig. 6: Configure the CanvasScaler object to fit the width of the screen.

For the reference resolution we are going to use 1920 x 1080 pixels, which is known as FullHD resolution.

The configuration of the CanvasScaler should be done at the beginning, before placing the elements of the graphical interface. Otherwise we will have to modify all the elements again to adjust them to the new configuration.

Fig. 7: Introducing FullHD resolution, 1920 x 1080.

We return to the GameObject image and adjust its size to 1920 x 1080 to cover the entire screen. If everything works well the screen should look like in figure 9.

Fig. 8: We adjust the size of the image so that it covers the whole screen.

Fig. 9: We should see the background of the scene obstructed by the image.

In the black color of the image we are going to make the Alpha component 0, this way it will be transparent.

Fig. 10: In the color of the image we set the alpha value to 0.

Now we are going to create a couple of buttons to execute the functions that we will later define in the Scripts.

Buttons

Fig. 11: Create a button to activate the black screen function.

We are going to call the first one BlackoutButton which is the one that is going to take care of darkening the screen completely.

Fig. 12: The button will be called “Blackout” as well as the function.

We adjust the sizes and colors to taste.

Fig. 13: We adjust the parameters of the button to taste.

We must make sure that the button is below the image in the hierarchy, that way the black screen will be drawn first and then the button, as we see in figure 14.

Fig. 14: The button must be visible even with the black screen.

Once we configure the Blackout button we are going to duplicate it and give it the name “PauseButton”, we accommodate it where we like on the screen. In figure 16 is my result.

Fig. 15: Duplicate the blackout button, move it down and give it the name “Pause”.

Fig. 16: With this the scene is finished.

C# Scripts

Now we are going to create two C# Scripts, the first one we will call “GameController” and the second “UIManager”.

Fig. 17: Let’s create two Scripts to control the elements.

Fig. 18: One script will be named “GameController” and the other “UIManager”.

The GameController Script is assigned to the GameObject with the same name. We can select it and drag it to the inspector or use the “Add Component” button.

Fig. 19: Select the GameObject GameController and use AddComponent to assign the GameController Script.

Fig. 20: The GameController Script is now a component of the GameObject.

The UIManager Script is assigned to the GameObject “UI”.

Fig. 21: Select the GameObject UI and with AddComponent assign the UIManager Script.

Fig. 22: The UIManager Script is now a component of the GameObject.

GameController Script

The GameController Script is responsible for indicating when the screen should be darkened and at what opacity value it should be set. It does not control the image object directly, this is the responsibility of the UIManager.

GameController will have two functions, one will be the Blackout function which will tell the UIManager to completely darken the screen and the other will be the Pause function which will cause the screen to darken 50%.

Fields and Initialization

We are going to define a UIManager type object to have the reference of the UIManager Script assigned to the GameObject UI in order to be able to access its public methods.

We’re also going to need two boolean variables to indicate if blackout and pause are enabled.

In the Start method we find the reference of the UIManager Script assigned to the GameObject UI with the instruction 13 shown in figure 23. Then we put in false the boolean variables.

Fig. 23: Fields and initialization in the GameController Script.

Methods

So that the Script fulfills the two functions that we said, we are going to define two public methods, one will be called “BlackoutFunction” and the other “Pause”. These methods will be executed when pressing the buttons of the graphical interface.

If you want to know more about methods I invite you to read this article I wrote earlier, talk about what a method is intuitively, there is also a video on the channel.

In the BlackoutFunction method the first thing we do is invert the state of the boolean variable blackoutActivated, so if it was in false now it’s going to be true and visceversa.

Then we check the state of that variable and we will execute a UIManager Script method with the appropriate parameter. At this point we have not yet written the “SetBlackoutOpacity” method of UIManager, so if you write lines 23 and 27 of figure 24 you will have an error.

In the Pause method we are going to do the same thing but instead of completely darkening the screen we are going to make it darken to half the opacity.

Lines 23, 27, 37 and 41 can be written after working on the UIManager Script.

Fig. 24: Blackout function and Pause function of the GameController Script.

UIManager Script

This script will control the parameters of the image to dim the screen.

In order to do so, it will constantly execute the Blackout function that will gradually modify the opacity of the image. In addition it will have a public method called “SetBlackoutOpacity” that will allow to tell the level of opacity wished, 0 means invisible black screen, 1 is completely visible black screen.

Fields and Initialization

To solve the behavior we are going to need an Image type object that we call “blackoutImage” and that we will mark with “SerializeField” so that it appears in the inspector.

We define a float called “blackoutOpacityChangeStep” to indicate the magnitude of opacity change in time, we also serialize it. Finally we define a float called “blackoutTargetOpacity” that will be the value that the opacity will tend to approach in each step of time.

In the Start method we make the objective opacity 0. We can see all this in figure 25.

Fig. 25: Fields and initialization in the UIManager Script.

Methods

We are going to define two methods, Private Blackout and Public SetBlackoutOpacity. Within the FixedUpdate method we will call the Blackout method, as shown in figure 26.

In the Blackout method we first read the current state of opacity of the image object (instruction 29 in figure 26).

If the opacity of that object is less than the objective opacity we will make it increase, if the opacity of the object is greater we will make it decrease. We achieve this with the “if” and “else if” of lines 31 and 39 respectively.

In order for the opacity to gradually increase or decrease we will create a new color to which we assign the same RGB components but to the alpha parameter we add or subtract the float “blackoutOpacityChangeStep”. In figure 26 we can see how to solve this.

The SetBlackoutOpacity method will be public and will take a float value as parameter. Simply assign this value to the variable “blackoutTargetOpacity”, as shown below in figure 26.

Fig. 26: UIManager methods to darken the screen at runtime.

We change the opacity value in the FixedUpdate method because we don’t want it to happen instantly but gradually to have a Fade In/Out effect.

Last settings

To be able to execute the GameController methods using the buttons, we have to do it in the OnClick() function of the button component.

Drag the GameObject GameController to the field under “Runtime Only” and using the drop-down menu select the “BlackoutFunction” method.

If it doesn’t appear in this list, we probably haven’t defined it as public.

With the button of Pause we do the same thing only that choosing the method Pause of GameController.

Fig. 27: In the Blackout button we execute the Blackout method of GameController.

Fig. 28: In the Pause button we execute the Pause method of GameController.

Finally select the GameObject UI and drag the GameObject BlackoutImage (with the image component, see figure 12) to the “Blackout Image” field. For the float “BlackoutOpacityChangeStep” we enter the value 0.1.

The result is shown in Figure 29.

Fig. 29: For the UIManager component we enter a value for the changeStep parameter.

Conclusion

In this article we saw a way to darken the screen in Unity. To achieve this we used a black image and modified the value of Alpha, which determines the opacity of the color. If the alpha is equal to 1 the color is totally opaque, if it is equal to 0, the color is totally transparent.

We configure two buttons to execute public methods of the GameController Script, which tells the UIManager object how should be the opacity of the black screen. UIManager finally makes the changes in the alpha value of the black screen.

Introduction

In this article we see a prototype of artificial intelligence for enemies in Unity.

These enemies will be in different states according to what happens during the game. The states are “Guard”, “Searching”, “Attacking”, “Covering”.

The idea for this prototype came about because a person wrote to me in the channel’s comments asking how you could get enemies to detect you, alert each other, warn others and attack.

To answer your question I created a project at Unity proposing an approach to the problem and made a video explaining how this prototype of artificial intelligence for enemies worked. You can see it below.

Download project files

You can download the project files to import and view the scripts in detail.

What are we gonna do with this?

At the moment it’s just a prototype that I made on a weekend and that meets the problem I was posed.

However everything can be improved, I am thinking of creating a more complex system based on this, improve the code, modularize more, create a better model for the weapon, separate the range of vision of the Enemy Script, improve in general the individual states.

The word “bit” comes from “binary digit”

Introduction – Numerical Systems

Before going into the main topic which is bit in computer science, let’s start from a mathematical approach.

A digit is a quantity of one figure that has a value and occupies a position in some numerical system. Let’s take as an example the decimal system that we use on a daily basis. This system is composed of 10 symbols that we call numbers (0,1,2,3,4,5,6,7,8,9). Each of these symbols has a value assigned to it and given two different numbers we can order them for example from least to greatest.

It is also said that the decimal system is a “positional system“, that is to say that a digit acquires value according to the position in which it is located. This is something we are taught at a very early age, the subject of “units“, “tens” and “hundreds“. The values 1, 10 and 100 are composed of the same digit 1, but they are not worth the same because that digit is in different positions. In other words the position in which a digit is found will have an associated weight, a 1 in third position is worth ten times more than a 1 in second position and one hundred times more than a 1 in first position.

Once a positional number system such as decimal has been established, we can begin to construct operations between numbers such as addition, subtraction, multiplication and division.

Are there numerical systems other than decimal?

The use of the decimal system is centuries old and it is thought that its origin lies in the fact that human beings are born with ten fingers. It is the numerical system that is mostly used worldwide, however nothing prevents us from using any number of symbols to establish a positional numerical system, for example if instead of using 10 symbols we use 8 we have the octal numeral system, on which the same mathematical operations of the decimal system are also defined.

Let’s think about the following example, in the decimal system the operation 9+1 gives as a result 10, where the 1 that is in the second position we know that it has a value or weight of ten. If we take this same example to the octal system, in which we have the numbers (0,1,2,3,4,5,6,7), the operation 7+1 gives as a result 10, where the 1 in the second position has a value or weight of eight.

Another known system is the hexadecimal system that has 16 symbols (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F), in this case the operation F+1 results in 10, where the 1 in the second position has a value of 16.

Another number system can be the binary system which is the one that interests us in this article, the binary system is composed of two symbols, zero and one, in this system the operation 1+1 results in 10, in which the 1 that is in second position has a value of 2. On the binary system can also be performed the operations of addition, subtraction, multiplication and division, but it has also been developed Boolean algebra that defines logical operations between binary numbers as the operations CONJUNCTION (AND) and DISJUNCTION (OR). And finally we come to the objective of this article, reiterating the opening sentence:

A “BIT” is a digit of the binary system.

What is a Bit in Computer Science?

In computing, the “bit” is the basic unit of information, which allows us to distinguish between two states.

Bits are grouped together to form binary words. A binary word of 8 bits is known as a Byte and allows us to represent 256 different states.

The processors in conjunction with RAM and ROM perform operations using binary words.

One way to understand how processors work is to study the different computer architectures. For more information, see the Von Neumann architecture.

So by using bytes (which are made up of bits) it is possible to represent increasingly complex information, not only numerical, but also text, sounds, images, and to perform logical and mathematical operations on that information.

For example, using 3 bytes we can represent any color in the RGB system, one byte for the red channel, one for the green channel and one for the blue channel.

Another example could be that using a byte we can represent a character, then a sentence will occupy a space in memory proportional to the number of characters that compose it.

What is the difference between BIT and BYTE?

Bit and Byte are two terms that are often confused or even used as synonyms, so let’s emphasize this. As we saw earlier, a BIT is a binary digit that can have a value of zero or one, while a BYTE is an ordered arrangement of EIGHT BITS. A bit allows us to represent two different states while a BYTE, being a combination of EIGHT BITS allows us to represent 256 different states, 2 raised to the 8 possible combinations.

The size of Information

I invite you to do a little experiment to see how much space information takes up in computers. The experiment consists of opening Notepad and pasting the following sentence without the quotation marks:

“The letters that make up this phrase occupy a certain amount of memory space.”

The previous phrase has 77 characters, take a look of the size of the .txt file.

Fig. 1: A txt file with 77 characters has a size of 77 bytes.

This is not always accurate because a text file does not store only characters, but also information about the format to display those characters. In addition, programs can use compression methods to represent the same information in a more compact form, however in the case of the notepad, the weight of the information is usually proportional to the number of characters, especially if there are only common characters.

What is a Bit at the Hardware level?

It is said that computers work with ones and zeros, this is true at a theoretical level, but physically the bits are implemented with voltage levels, think of the lamp in a room that is turned on or off with a switch, when the switch is open, electricity does not flow and the lamp is off, when the switch is closed, electricity flows and the lamp is turned on, this example is similar to what happens inside the digital microchips, where there are extremely small switches (the size of dozens of atoms and every time they try to make them smaller) that open or close in a controlled manner, ie prevent the passage of electricity or allow it, in other words at the output of that switch we can have a 0 or a 1. These small switches are called TRANSISTORS.

Microprocessors are systems made up of millions of transistors. Using transistors it is possible to create logic gates, from the most basic gate which is an INVERTER that implements the logical operation NOT, that is to say if the input is 0 the output will be 1, to more complex gates such as the XOR gate, that given two input bits, the output will be 1 if and only if one of the inputs is 1. In addition these logic gates are grouped in increasingly complex digital systems to form flip flops, counters, adders, shift registers or memory blocks.

RAM is another example, a block of volatile memory, which stores bits temporarily to assist the processor with its tasks.

The hard disk stores bits in the form of magnetic fields using the magnetic hysteresis property of some materials, while solid state disks store information in flash memory blocks, with no moving parts.

Conclusion

A bit is a binary digit that can be worth 0 or 1, it is part of a numeric system analogous to the decimal system we use, the binary system, in which instead of having 10 numbers, we have two.

The bit is the basic unit of information used in computing. By grouping bits into binary words, all kinds of data such as numbers, text, images or sounds can be represented, i.e. information can be digitized.

The bit is a concept that is applied at the software level to analyze the information and logical operations that are performed. In microprocessors this translates physically to voltage levels or magnetization in the case of magnetic hard drives.

Introduction – Project Setup

In this article we will learn how to use console messages to analyze how our code works and eventually detect and correct bugs.

To start we are going to create a new project in Unity, in my case I am going to call it Debugging.

Fig. 1: Initial scene to study the Debug.Log method.

In the process of detection and correction of bugs we are going to use mainly the console of Unity, in that window will print messages that we will strategically place in our code.

Fig. 2: Console tab in Unity 3D.

If the console window is not active, you can open it from the Window tab as shown in figure 3.

Fig. 3: Path to open the console in Unity 3D.

The next step is to create a new C# Script, we can do it from the project window as shown in figure 4. I’m going to give it the name “Debugging”.

Click here to know more about Scripts in Programming

Fig. 4: Create new C# Script.
Fig. 5: The C# script is called Debugging.

For the code of our Script to run in general it is not enough to create the Script, it must also be assigned to at least one GameObject of the hierarchy. Let’s create an Empty GameObject and give it a meaningful name.

Then with that GameObject selected we drag the Script towards the inspector to assign it (figure 8).

Fig. 6: Create new Empty GameObject in the hierarchy.
Fig. 7: We give the GameObject a name.
Fig. 8: The Script created previously in the inspector is assigned.
Fig. 9: The Debugging Script has been assigned in the inspector.

Programming C# Unity – Debug.Log

When opening the Script (figure 10) we see that there is some code that is written by default. The basic libraries are imported and we have the Start and Update methods which run automatically.

In my channel there is a video about what a programming method is and also an article on this page.

Fig. 10: Default content of a C# script.

We are going to write an instruction in the Start method. This instruction is the execution of the Log method of the Debug class, to which we will pass the message to print.

As can be seen in figure 11, the instruction is:

Debug.Log(“Este mensaje aparecerá en la consola”);

Which means: “This message will appear in console”.

Fig. 11: We write the Debug.Log instruction in the Start method.

We enter the game mode to test the Script, for this we use the Play button of the Editor (figure 12).

Fig. 12: Button to enter the game mode.

Fig. 13: In the lower left corner of the program the console messages also appear.

You can see that the message appears in the lower left corner of the program without having the console open.

In figure 14 I separated the console window to better visualize the information.

Fig. 14: Message in console, on the right appears a number indicating the number of times the message is sent.

Let’s see what happens if we put a message in the Update method.

Fig. 15: Another message is placed in the Update method.

To the right of the message is a number indicating the number of times the message is printed.

As can be seen in figure 16, the message of the Update method has been printed 82 at the time of capture while in figure 17 the message has been printed 350 times.

Fig. 16: Capturing messages in the first seconds of the game.
Fig. 17: Capturing the messages a few moments later.

Using Variables

The messages that we want to print in console can be stored in variables and the result is the same.

Fig. 18: Two strings are defined with the messages and placed in the methods.

Let’s create some more variables, an integer, a boolean and a float. These three types of variables together with the String are the basic types of variables that we are going to use in any project.

In the channel there is a video about “What is a Variable in Programming” and I also wrote an article for this page.

Fig. 19: A variable is defined as integer, bool and float, each with values.

As can be seen in figure 19, we are going to declare them and initialize them with a value. We can do this in different points of the Script, but we will do it at the beginning of the class, before the Start method.

Then we are going to execute three Debug.Log methods passing as parameter the variables.

Fig. 20: Debug.Log is executed with the new variables.

When you enter game mode, all four messages appear on the console.

Fig. 21: The console displays the value of each variable.

In previous versions it was necessary to execute the ToString() method in order to print the value of a variable that is not a string, as shown in figure 22, this can be done but is no longer necessary, you can pass the variables directly.

Fig. 22: Execution of ToString() that converts the value of the variable into text.

We are going to define 4 new variables, one of each type and give it different values, as shown in figure 23.

Fig. 23: More variables are defined to perform operations.

We can make the console print the result of operations with variables, as shown in figure 24.

If we compare the values in figure 23 with the console prints seen in figure 25, we can verify this.

Fig. 24: Operations are entered in the parameter of the Debug.Log methods.

Fig. 25: The results of these operations are printed on the console.

It is also possible to concatenate different types of variables and print a message.

Fig. 26: Different types of variable can be concatenated to form the message.
Fig. 27: Message made up of different types of variables.

Frame Counter

Previously we placed a Debug.Log instruction in the Update method, which contained a fixed message.

We are going to print a message that is going to change frame to frame.

Fig. 28: An integer is defined to count the number of frames that pass.

To start with we define an integer to count the frames and initialize it in the value 0.

Let’s concatenate the message “This is the frame: ” (including the final space), with the counter value.

After displaying the message in console, we increase the counter so that in the next frame it indicates the next frame number.

These two instructions are shown in Figure 29.

Fig. 29: A message is printed with the frames count and then the counter is increased.

Figures 30 and 31 show the execution of this code at two different times.

Fig. 30: Messages in the first seconds of execution.
Fig. 31: Messages appearing moments later.

Elements of an Array or Integer Vector

Now we are going to apply the Debug.Log Method to analyze the elements of an Array.

An Array is an ordered structure of data of some kind upon which operations can be made. This data structure is like the mathematical vector.

First we are going to declare an Array of integers, this is similar to declaring an integer only by adding the square brackets after the type, as seen in Figure 32.

At the same point we are going to create the Array with the values seen in figure 32.

Fig. 32: A vector of integers with different values is defined.

We are going to read the Array in the Start method, first we are going to write a message indicating the size of the vector.

To go through the Array we use a “for” loop that starts from 0 to the amount of Array elements minus one.

Inside the for loop we are going to print a message in console using Debug.Log and concatenating text with the values of the variable.

Fig. 33: In the Start method we are going to analyze the array using Debug.Log.

In this way using the console we can study the array and its elements, as can be seen in figure 34.

Fig. 34: Console messages that give us information about the Array.

Print the result of the execution of a Method

If we have a method that returns a variable, we can apply it as a parameter of the Debug.Log method, as shown in figure 35.

The method “UnMetodoExcelente” is defined which returns a string.

The execution of this code is shown in figure 36.

Fig. 35: A method is defined that returns a string to print message in console.
Fig. 36: The message consists of the string returned by the method.

The same could be done with a method that requires parameters, as shown in figure 37.

Fig. 37: A parameter is added to the method.
Fig. 38: The message depends on the parameter we give to the method.

Debug.Log to analyze the result of an if statement

The flow of our program can move in different ways depending on the data, for example in a sentence if, the flow of the program will take one of two possible paths depending on the Boolean variable being evaluated.

In figure 39 we define the if sentence, which will execute one method or the other. Each method prints its characteristic message.

Fig. 39: Two methods are defined, one of which will be called randomly.

In figures 40 and 41 we see the execution in two different moments of the game.

Fig. 40: In this case the BadPath method was executed.
Fig. 41: In this case the “GoodPath” method was executed.

Conclusion

The Debug.Log method is used to write messages in the console.

By strategically placing these messages in our code we are able to visualize the flow of the program, get information about the state of our variables and objects.

The Debug.Log method takes as parameter a variable that can be in principle string, bool, int or float, the basic types of variables that we have analyzed in other articles.

These parameters can be delivered in different ways, for example it is possible to create a message concatenating variables, as the result of a method, enter the variables directly or enter the operations whose results we want to be printed.

Introduction

In this article we are going to see what a script is in programming, we are going to write a simple script in the notepad that does a certain task and give several examples of application.

Script in programming

In simple terms a programming script is a text document where we place instructions or commands that will then be executed by an intelligent device.

These instructions will be written in some programming language in which their syntax must be respected so that each instruction can be translated into machine language. In addition, each script will be a file with a format that will depend on the language in which it is written.

All the scripts of our program make up the source code.

Let’s write a Script right now!

The field of application of programming is very wide, we can write programs for a number of purposes. I invite you to perform the following experiment for the Windows platform:

Let’s open Notepad, that application that has always been in Windows.

Let’s write the following two lines:

timeout /t 6000 /nobreak

shutdown -h

It should look like this:

Fig. 1: Script made in Notepad. When running, the computer waits 6000 seconds and then goes into hibernation.

We click on “file-save file as” and make sure to choose the option “All Files (.)”, as shown in Figure 2. We give it a name and end it with the extension “.bat” which is the Batch extension or batches. Let’s save it on the desktop to find it quickly.

Fig. 2: Save How window of Notepad. Put the extension “.bat”.

We are generated a Batch file that we can execute by double clicking, figure 3.

Fig. 3: File generated when saving with the extension.

When executing it, the windows terminal opens indicating that it is waiting for a certain amount of time that we have indicated in our Script.

Fig. 4: Execution of the “hibernar.bat” script.

When the 6000 seconds indicated in the script are reached, the second instruction will be executed: “shutdown /h” that will put our equipment in hibernation state.

That’s how easy it is to write a script that fulfills a certain function!

This script is very useful to me to put the computer to hibernate automatically after a certain time, avoiding that it remains on all night.

Other examples of Scripts

Next I’m going to show a series of examples of Scripts that we can find when starting a project that involves programming.

Games made with Unity

If we want to develop a game in Unity, we are going to find the Scripts in C# language. If we want we can write these scripts in Notepad as long as we save them with the extension “.cs”, but that would be unnecessarily complicated. We have Editors that allow us to check the syntax, auto complete and make the job easier.

Fig. 5: Script in c# belonging to the development of the series “Fundamentals of Unity”.

If you’re interested in learning how to make games at Unity, I invite you to watch the My First Game series at Unity and the new Unity Fundamentals series I’m currently working on. There are videos, articles and files to download.

Android Applications

Maybe you are interested in making an App for Android, in that case an option is to use the Android Studio software.

XML Scripts are used to define the design of our application and logic using Java Scripts. Figures 6 and 7 respectively.

Fig. 6: XML script for the design of an application in Android Studio.

Fig. 7: Java script for the design of an application in Android Studio.

To study programming I have used development environments such as Eclipse or NetBeans, in which I have written Scripts in Java that I could then simulate in the console and analyze the results. Here is an example of a Java script using the NetBeans IDE:

Integrated Development Environments (IDE)

Fig. 8: Java script using NetBeans IDE. The Script is for the study of concurrent programming.

Arduino Projects

Maybe we’re interested in electronics and want to program an Arduino. In that case we are going to write scripts in “.ino” format using the Arduino IDE.

Fig. 9: Arduino default script.

Speaking of Arduino, I leave a video that I uploaded to my channel some time ago about a project in which I used Arduino Mega and sent the information to a simulation made in Unity. The models are made in Unity. I think it would be nice to make a series of videos with a project to combine electronics and game development, just for fun.

Simulación de proceso industrial hecha en Unity
 🟢

Other examples can be Scripts for MatLab or SciLab, plugins for Blender, Scripts to process data in Excel tables, scripts to run macros and many other examples.

Conclusion

Scripts in programming are sets of instructions written in some language and that later will be executed by an intelligent device, be it a computer, a mobile phone, and so on.

The field of application of programming is very wide. Depending on what we want to do we will have different tools to write Scripts and these will be in different formats.

Introduction

In this article we are going to see how the OnTriggerExit method works in Unity. This function will allow us to know when the Collider of a certain GameObject, that was previously inside another Collider, has exit.

OnTriggerEnter and OnTriggerExit are very similar methods but it changes the moment in which the execution of these methods happens, knowing exactly these moments will allow us to build solutions.

The following video has summarized information about the OnTrigger events, how to setup the components and how to define the events in a script.

OnTriggerExit Method in Unity

The OnTriggerExit method is defined in the MonoBehaviour class. That is to say that any new Script by default will have it by inheritance.

Several conditions must be met for OnTriggerExit to run.

The first is that there must be two GameObjects with Colliders involved, one of the Colliders must be in Trigger mode, for this you must check the box “Is Trigger” in the inspector.

In addition, at least one of the GameObjects involved must be assigned a RigidBody component, because OnTriggerEnter is related to the physical part of the engine.

Declare OnTriggerExit

The fact that it is defined in the MonoBehaviour class and a new default Script does not mean that we will automatically have OnTriggerExit in our Script, we must declare it and we do it in the following way:


private void OnTriggerExit(Collider c){

//Acciones a realizar cuando se detecta una entrada al Trigger.

}

If the conditions are met, this method will run automatically, so inside we write everything that needs to be done when that happens.

The parameter “Collider c” that receives the method, is the Collider of the GameObject that came into contact with the Trigger. We can use this parameter to do many things, for example get the GameObject that has assigned that collider, we do this simply with:

c.gameObject

From there we can read any other component assigned to GameObject, its tag, its layer, modify what we need and we are allowed to modify, execute methods defined in Scripts that may be assigned and many more actions.

To learn more about programming functions with parameters I invite you to read this article.

Conclusion

The OnTriggerExit method allows us to detect when a GameObject ceases to be in contact with a Collider in Trigger mode and we can execute the desired actions when that happens.

OnTriggerEnter runs automatically, for this to happen there must be some conditions, the first is that there must be two GameObjects with Colliders involved and one of them in Trigger mode and the second is that at least one of the GameObjects must have a RigidBody component assigned.

Introduction

In this article we are going to see how the OnTriggerEnter method works in Unity. This function will allow us to know when the Collider of a certain GameObject has enter another Collider that is specially configured to be able to detect.

OnTriggerEnter and OnTriggerExit are very similar methods but it changes the moment in which the execution of these methods happens, knowing exactly these moments will allow us to build solutions.

The following video has summarized information about the OnTrigger events, how to setup the components and how to define the events in a script.

OnTriggerEnter Method in Unity

The OnTriggerEnter method is defined in the MonoBehaviour class. That is to say that any new Script by default will have it by inheritance.

Several conditions must be met for OnTriggerEnter to run.

The first is that there must be two GameObjects with Colliders involved, one of the Colliders must be in Trigger mode, for this you must check the box “Is Trigger” in the inspector.

In addition, at least one of the GameObjects involved must be assigned a RigidBody component, because OnTriggerEnter is related to the physical part of the engine.

Declare OnTriggerEnter

The fact that it is defined in the MonoBehaviour class and a new default Script does not mean that we will automatically have OnTriggerEnter in our Script, we must declare it and we do it in the following way:


private void OnTriggerEnter(Collider c){

//Acciones a realizar cuando se detecta una entrada al Trigger.

}

If the conditions are met, this method will run automatically, so inside we write everything that needs to be done when that happens.

The parameter “Collider c” that receives the method, is the Collider of the GameObject that came into contact with the Trigger. We can use this parameter to do many things, for example get the GameObject that has assigned that collider, we do this simply with:

c.gameObject

From there we can read any other component assigned to GameObject, its tag, its layer, modify what we need and we are allowed to modify, execute methods defined in Scripts that may be assigned and many more actions.

To learn more about programming functions with parameters I invite you to read this article.

Conclusion

The OnTriggerEnter method allows us to detect when two GameObjects overlap their Colliders, so we can apply all the necessary actions.

OnTriggerEnter runs automatically, for this to happen there must be some conditions, the first is that there must be two GameObjects with Colliders involved and one of them in Trigger mode and the second is that at least one of the GameObjects must have a RigidBody component assigned.

Let’s begin with a video on this topic:


Introduction

This is the last exercise in Unity’s Fundamental Series, in this article we’re going to see how to change the scene in Unity at runtime.

Understanding how to change the scene is important because it allows us to separate the content of our game into parts, for example the main menu on one side and the game itself on the other. Another example could be a village with different buildings in which you can enter, the village can be built in a scene and then use multiple scenes for each building, or use a scene for all buildings and choose the appropriate one at the time of loading the scene.

Go to the project’s main page

Before we start I invite you to watch the video I made to summarize this article. English Subtitles available.

Maybe you find it useful…

I invite you to see this article and its respective video on how to achieve a Fade In / Fade Out effect in Unity, you can apply this to what we see in this article to achieve a change of scene not abrupt.

GO TO THE SOLUTION – FADE IN/OUT EFFECT FOR UNITY

Fade In – Fade Out Effect for Unity
👉

PLEASE CONSIDER SUBSCRIBING TO MY CHANNEL

Scenes in Unity

Each scene in Unity contains its own hierarchy of GameObjects, depending on our needs we can use them in different ways.

Some simple examples of using scenes are using one scene for the menu and another for the game, each scene is a level of our game, do everything in a single scene, etc..

In our projects we probably have to make changes of scene, that’s why I consider it part of one of the fundamental things of Unity.

GameDevLab LoadScene Station

To learn how to change a scene in Unity we’re going to use GameDevLab’s LoadScene station, which consists of a strange well that looks like it disintegrates matter and sends it through space-time.

Fig. 1: Front view of LoadScene station.
Fig. 2: Inside the well of the LoadScene station.
Fig. 3: Inside the well of the LoadScene station.

At the bottom of the well there is a capsule (figure 4) that has a Collider assigned in trigger mode and a Script that will detect the character and send a message to the Script that we have to complete.

Fig. 4: At the bottom there is a capsule with Collider in trigger mode.

The complete station is contained in the GameObject “#10 LoadScene” of the hierarchy, this GameObject is assigned the Script “LoadScene” which is the Script we have to complete in this exercise.

Fig. 5: Project hierarchy.
Fig. 6: LoadScene station components.

The Script to complete contains a single public method called “teleport”, this method will be executed by the capsule Script when the character is detected at the bottom of the well.

If it is not clear what a method is in my channel there is a video in which I talk about methods in programming (english subtitles available) and there is also an article in the programming section of this page.

Fig. 7: LoadScene script to complete.

What we are going to do is change the scene within the method “teleport”, for this we go to the folder scenes of the pack of the fundamental series and we see that there are two scenes (figure 8), one is the GameDevLab and the second scene is GameDevDimension, the latter is the one we are going to load using its name.

Fig. 8: Scenes from the project, GameDevLab and GameDevDimension.

Solution

To start with we have to import the namespace UnityEngine.SceneManagement

Fig. 9: Imported libraries at the top of the script.

Then to change the scene in Unity we execute a static method of the “SceneManager” class, the LoadScene method, to which we pass as parameter a String with the name of the scene we want to load.

Fig. 10: Method to change the scene in Unity.

With that simple instruction we can make the scene change, but for this to work all the scenes have to be added to the compilation, this we do in File > Build Settings, opening each scene and clicking Add Open Scenes.

Fig. 11: Scenes are added in Build Settings.

When the character falls into the pit a new scene is loaded in which the camera automatically advances and the controls are disabled, when the camera reaches the end of the tunnel the GameDevLab scene is automatically loaded again.

Fig. 12: Entering game mode and falling into the pit loads the GameDevDimension scene.


Fig. 13: Tunnel view of the GameDevDimension scene.

Fig. 14: Tunnel view of the GameDevDimension scene.

Fig. 15: Tunnel view of the GameDevDimension scene.

Conclusion

To change a scene in Unity we need to import the UnityEngine SceneManagement library and use a static method of the SceneManager class.

We can refer to a scene by its name or by its identification code that appears in Build Settings, in this case we use the name.

Loading a new scene is a relatively simple task, the problem is that the new scene is predefined and always starts from scratch.

For example a scene can be a house with ten coins, the character enters, takes the coins and leaves the house, ie returns to the previous scene. If we do nothing about it, when we re-enter the house scene the ten coins will be inside again.

To prevent this we have to store information of the state of the variables in the scene and read this information at the beginning of the scene.

Introduction

In this article we’re going to see how to rotate objects in Unity. There are several ways to achieve this, in this case we will use the Rotate method of the Transform class, this will directly modify the rotation parameters that are observed at the top of the inspector with the GameObject selected.

Go to the project’s main page

Before we start I invite you to watch the video I made to summarize this article. English Subtitles available.


How are rotations expressed mathematically?

In order to describe mathematically we have to know directly or indirectly the following parameters:

-Rotation axis

-Amount of angles to rotate

-Sense of rotation

Let’s imagine that the object we want to rotate is a sphere. We take it in our hands and stick a rod through the exact center of the sphere. Then we take the rod and orient it from north to south parallel to the ground. Finally we make it turn counterclockwise.

Were you able to visualize it in your mind?

My description of the rotation was accurate although perhaps it was not drafted in the best way to be understood. However, let us assume that we could all have imagined exactly the same thing.

In the first place we can say that the axis of rotation is the rod. If we become strict the axis of rotation is an imaginary line that passes through the two ends of the rod.

The number of angles to rotate is half a turn, this mathematically is 180° or π radians.

The direction of rotation is counterclockwise or counterclockwise.

These three parameters can be fully described using a vector, which is what we are going to do in this article.

Workstation

We are going to use the rotation station which consists of three gears that are oriented in the direction of the world’s three x,y,z axes.

Fig. 1: Front view of the gear mechanism to be used.

The three gears are positioned perpendicular to each other.

Fig. 2: Side view of the gear mechanism to be used.

In the hierarchy we can find them inside the GameObject “#9 RotateObjects”. They have the names GearX, GearY and GearZ indicating the axis of rotation of each gear.

Fig. 3: In the hierarchy we have a GameObject for each gear.

The script to complete is called “RotateObjects” and is assigned to GameObject with the same name in the hierarchy.

In figure 4 we see that the three GameObjects of the hierarchy are already assigned in the fields of the inspector.

Fig. 4: The gears are assigned in the fields of the Script Rotate Objects.

When opening the Script we find the FixedUpdate method defined and inside some comments that say that the gears must be rotated there.

If it is not clear what a method is in my channel there is a video in which I talk about methods in programming (english subtitles available) and there is also an article in the programming section of this page.

Why should the rotation code go in the FixedUpdate method?

In the Article 1 about reading keyboard and mouse inputs we discussed why reading instructions were in the Update method.

The FixedUpdate method as its name indicates is an update of the object state but executed at a certain fixed time.

This means that no matter how much the frame rate of the game changes, we will have the same number of executions of this method per second.

Colocaremos en el método FixedUpdate una instrucción que hará que los engranajes giren una determinada cantidad de ángulos en algún sentido respecto de un eje. Esto significa que en cada llamada de FixedUpdate se aplicará la rotación, lo que generará un movimiento continuo de rotación.

Fig. 5: Fields defined in the RotateObjects Script.

Fig. 6: Script when first opened. The FixedUpdate method is defined.

Solution

The Rotate method of the Transform class has different versions, we are going to use one in which the first parameter is the vector that completely expresses the rotation and in the second parameter we indicate the type of coordinates to use, global coordinates that are unique in the whole world of the game or local coordinates that are specific to each particular object, which would be as if each object had its own north.

Fig. 7: Instructions for rotating each gear in relation to its own axis.

By mathematical properties of the vectors I rewrote the vector as the product of its module or norm multiplied by a unit vector (norm 1) describing the direction.

This allows us to separate on the one hand the direction of rotation and on the other hand the number of angles to rotate.

Fig. 8: Modifying the variable in the inspector we can change the speed of the set of gears.

Another advantage of expressing the vector that way is that we can change the direction of rotation simply by using negative values in the inspector.

Fig. 9: Using negative values the rotation of the gear set can be reversed.

Conclusion

You can simply rotate objects in Unity using the Rotate method of the Transform class.

If we don’t need mathematical precision, we can play with numbers and get different results.

With this type of rotation we directly affect the rotation vector of the Transform component, this is fine if we seek to show only the animation rotation. If the rotation is needed to produce physical interactions, RigidBody should be used.

IMPORTANT UPDATE

This article belongs to an old series of the channel, currently there is a video available that explains better how to use the Invoke function to make a function be called with delay, you can watch it here:

🟢 How to DELAY a FUNCTION using INVOKE method


Old Article below

Introduction

In this article we are going to see how to use the Invoke method of Unity’s MonoBehaviour class to execute an action with a certain delay. This allows us for example to create mechanisms that work for a while.

Go to the project’s main page

Before we start I invite you to watch the video I made to summarize this article. English Subtitles available.

Procedure

To analyse the Invoke method we’ll be using the GameDevLab’s “Invoke a Method” station, which is a vending machine for the refreshing new GameDevCola that not only quenches thirst but also heals your wounds.

Fig. 1: GameDevLab “Invoke a Method” station. GameDevCola vending machine.

By approaching the machine we can interact with it using the E key. When you press it, the machine will become inactive, that is, you will not be able to interact with it for a while. After a few seconds the machine will eject a can of GameDevCola and seconds later will again be enabled for interaction.

Fig. 2: Script InvokeAMétodo sin completar.

In the script to complete we have the methods “DeliverACola” and “PrepareMachine” that will deliver the drink and enable the machine respectively.

Then we have redefined the OnTriggerStay method that allows us to check if the character is standing in front of the machine.

Here is the article that analyzes the OnTriggerStay method.

Within this method we check if the Tag of the GameObject is that of the player, then if the machine is ready (boolean machineReady), we tell the UIManager object that can interact and this is responsible for displaying the message on screen.

Then we check if the E key is pressed. At this point the machine receives a request for a GameDevCola. The first thing you do is deactivate the machine and then in the region with comments is where we must complete the missing code.

Analysis of events in time

I want to emphasize this part because it is important to understand the idea.

When we call a method in C#, the execution of it is done at that precise instant, all instructions are solved even before refreshing the screen image.

So if we called the methods directly in the region marked with comments, what would happen is that the can would be expelled and the machine enabled again in the same instant in which the E key is pressed. As illustrated in the timeline in figure 3.

Fig. 3: Diagram of events in time. This would happen if we called the methods directly.

Figure 3 shows a timeline in which there are two different points in time, the first point being the beginning of the game. Sometime later in time is the second point, in which the player asks for a can, the machine delivers it and it is enabled again, these three actions at the same time.

Fig. 4: Diagram of events in time. This is what we want to achieve.

Figure 4 shows four different time points.

Point 1: Start of the game.

Point 2: The player orders the GameDevCola.

Point 3: X milliseconds after the order is placed, the machine delivers the can.

Point 4: After Y milliseconds of can delivery, the machine is enabled again.

This is what we are going to do using the Invoke method of the MonoBehaviour class.

Solution

The Invoke method can be called directly without reference to a class.

We must indicate two parameters, the first is a String with the name of the method we want to invoke, the second parameter is a float to indicate the number of seconds that will pass until the method is finally executed.

Upper and lower case must be respected. If we get confused at this point, a bug may arise that is difficult to track. If the method is called “DeliverACola” and we invoke the “DeliveraCola” method what will happen is that we will try to call that method but as it is not defined, the program will go ahead without executing those instructions.

Fig. 5: InvokeAMethod script completed.

Figure 5 shows the resolution for the exercise. The can will be delivered two seconds after the player presses the E key and the machine is re-enabled four seconds later.

Fig. 6: When approaching the machine, a sign appears indicating that it is possible to interact.

Fig. 7: After a few seconds of interacting with the machine, we are given a can.

Conclusion

The Invoke method is used to postpone the execution of a method. Although it is not the only way to achieve this, it is a simple resource, easy to remember and easy to implement.

Introduction

In this article we are going to study how to use the AddForce method of Unity’s RigidBody class, which allows us to apply forces to GameObjects that have a RigidBody component assigned to them. The goal is to make the ball in the GameDevLab bounce indefinitely for the duration of the game.

Go to the project’s main page

Procedure

We are going to use the “AddForce” station, which consists of a diamond-shaped container with a ball inside. The objective is to make the ball bounce indefinitely inside the station. To do this we must apply a force when the ball hits the bottom.

Fig. 1: GameDevLab AddForce Station.

In the hierarchy we have the GameObject “#7 AddForce” that contains all the elements of the station (figure 2). This GameObject is also assigned the Script “AddForceToObject”.

Fig. 2: Hierarchy of the GameDevLab. Let’s work with the GameObject “#7 AddForce”.

Fig. 3: Componente “AddForceToObject” asignada al GameObject “#7 AddForce”.

In figure 3 we see the “AddForceToObject” component in the inspector. We can assign an object to which to apply the force, in this case is “Sphere” the ball that is inside the station. We can assign a minimum and maximum force value to apply to the ball and the direction of the force.

Fig. 4: To the left, the sphere of the “AddForce” station. On the right, its components are displayed in the inspector. Between them there is a RigidBody component that will give you physical behavior.

The Ball GameObject is simply a primitive sphere made in Unity, it is assigned a RigidBody component that gives it physical behavior. The ball will be affected by gravity, it will be able to collide with objects that Colliders have assigned and we will be able to apply forces to it.

Fig. 5: To the left the GameObject in charge of detecting if the ball touches the ground. To the right its components in the inspector.

At the base of the structure we have a cylinder-shaped GameObject that has a Box Collider assigned in Trigger mode (figure 4). It also has a script called “AddForceCollisionDetection” that will detect the ball.

Solution

When we open the “AddForceToObject” Script for the first time we find what you see in figure 6. All the parameters you see in the inspector are defined and it contains only one method called “addForce”. This method is defined as public because it is the one that is going to be called when it is detected that the ball has touched the ground of the structure.

Fig. 6: Script “AddForceToObject” incompleto.

The solution of this exercise is shown below and the purpose of each instruction is explained.

Fig. 7: Solution of the exercise.

To solve this problem we will require three instructions. The first will define the magnitude of the force to be applied, which will be a random value between the minimum and maximum forces.

The second instruction will define the total force to apply, if you saw the video about physics, to define a force we need a magnitude and a direction. For the direction we use the vector of three dimensions (class Vector3) that is seen in the inspector, it is called “forceDirectionVector”. But we are not going to use it as it is written in the inspector. To prevent that Vector3 from affecting the magnitude of the force we must normalize it. We do this with the “Normalize” method of the Vector3 class. The total force to apply will be a Vector3 called “force” which is the result of multiplying the direction by the magnitude.

Finally the third instruction consists in applying force on the object. The forces are applicable to GameObjects that have a RigidBody component assigned, in our case we are going to apply the force on the RigidBody component of the ball. We use the “GetComponent” method to obtain the RigidBody component and finally we execute the AddForce method, passing as parameter the force to apply.

Fig. 8: Station running. The ball bounces with variable force.

Conclusion

When testing the game, the ball rebounds indefinitely with a random force.

To define a force we need a real value for the magnitude and a vector for the direction in which it should be applied.

The forces act on the RigidBody component of a GameObjects.

IMPORTANT UPDATE

This article is part of an older video series, I recently upload a Unity prototype to help understanding how the OnTrigger system works, how to configure the objects from the scene and how the functions are called.

The following video has summarized information about the OnTrigger events, how to setup the components and how to define the events in a script.


OLD ARTICLE BELOW

Introduction

In this article we are going to study how to use the OnTriggerEnter (Collider c) and OnTriggerExit (Collider c) methods to detect the player in a given region and apply actions when that happens. Specifically we are going to make the GameDevLab door open when the player is in front of it and close when it moves away.

Go to the project’s main page


Procedure

We are going to use the “OnTriggerEnter/Exit” station, which consists of a portal that leads to a small room that for now has nothing special.

Initially the door is closed, our goal is to detect the character when he approaches and open the door to let him in and away from the portal the door must close.

Fig. 1: GameDevLab OnTriggerEnter/Exit Station.

All elements of the station are contained in the GameObject “#6 OnTriggerEnter/Exit”.

Fig. 2: Hierarchy of the GameDevLab. Let’s work with the GameObject “#6 OnTriggerEnter/Exit”.

This GameObject is assigned the script “OnTriggerEnterExit” which is the one we have to complete on this occasion.

Fig. 3: Components of the GameObject “#6 OnTriggerEnter/Exit”. We have assigned the Script to complete in this exercise and a Box Collider in trigger mode.

In addition to a Mesh Collider so that the character does not cross the structure, it also has a Box Collider in Trigger mode, as seen in figures 3 and 4.

Fig. 4: Box Collider in trigger mode that we will use to detect the character.

Let’s use this Collider to solve the exercise.

Fig. 5: Opening the door once we solve the exercise.

Fig. 6: View from inside the room.

If you want to know more about Colliders I invite you to watch this video I made for the series “My First Game in Unity”.

Resolution

When we open the OnTriggerEnterExit Script for the first time we find two methods, the openDoor() method that will open the door and the closeDoor() method that will close it.


Article: What is a method in programming?

In addition, the region where the redefinition of the OnTriggerEnter(Collider c) and OnTriggerExit(Collider c) methods is suggested is indicated with green comments.

Fig. 7: Script OnTriggerEnterExit sin completar.

We’re not going to worry about how the door opens and closes because that’s already solved in GameDevLab.

How the OnTriggerEnter(Collider c) and OnTriggerExit(Collider c) methods work

In the previous article we saw how the OnTriggerStay method worked and we used it to make the damage and regeneration stations affect the player’s health.

Article: OnTriggerStay Method

For the OnTriggerEnter and OnTriggerExit methods the same requirements are needed, what changes is the moment they are executed.

Fig. 8: Components required for the operation of the methods.

Fig. 9: The OnTriggerEnter method is automatically executed on the first frame in which a collider enters the trigger.

OnTriggerEnter runs the moment the player enters the trigger for the first time, i.e. the previous frame of the game was outside the trigger and the current frame is inside.

Fig. 10: The OnTriggerExit method is automatically executed on the first frame in which a collider exits the trigger it had previously entered.

On the other hand, the OnTriggerExit method is executed at the moment in which the player leaves the trigger, that is to say in the previous frame of the game it was inside the trigger and in the current frame it is outside.

Fig. 11: Overview of the operation of the methods.

With this in mind, what we can do is open the door in the OnTriggerEnter method and close it in the OnTriggerExit method.

In addition we are going to verify that the tag of the Collider that entered in the trigger is equal to “Player”, of that form we know that it is about the player. The following figure shows the resolution.

Fig. 12: Resolution of the exercise within the region defined by the green comments.

Conclusion

The OnTriggerEnter and OnTriggerEnter methods allow us to detect GameObjects that enter a certain region, this has a number of applications, for example activate kinematics, mechanisms, allow us to perform certain actions only when we are in a certain region, and so on.

Unlike the OnTriggerStay method, these methods are run only once when one of the above situations occurs.

Introduction

In this article we are going to see the absolute value function of a number, what are its properties, some graphics and as an extra we are going to see how to calculate the absolute value of an expression in the Unity graphic engine, in the field of programming and game development.

Definition of the Absolute Value of a Number

The absolute value of a number is the distance between that number and the 0 of the measurement system.

This results in two possible outcomes depending on the number in question.

If the number is positive, the result of taking the absolute value is the same number. If on the other hand the number is negative, when taking the absolute value the result is the same number but in positive value.

Formally:

   

Because of this definition we can affirm that the absolute value of a number is always a positive number.

Graph of the Absolute Value of X

Below are some graphs of the absolute value function to understand how it behaves.

Observe in each graph the ranges of the variables in the axes to see how the graph is affected by the displacements in X in Y and by the coefficients that multiply the expression.

(1)  

(2)  

(3)  

(4)  

Distances

When we are working with different points in a coordinate system, we are often interested in working with the distances between them, which are positive values.

The absolute value allows working with these distances in mathematical expressions.

How to calculate the Absolute Value in Unity

To calculate the absolute value of an expression in Unity, we must make use of the static method “Abs” of the class “Mathf”.

Let “num” be a numerical variable defined in the program in question, to take its absolute value we do:

Mathf.Abs(num);

The result of the execution of this method can be stored in another variable or in the same one, in the following way:

num = Mathf.Abs(num);

Introduction

In this article we are going to talk about the summation and product notation, what they mean and how to perform the calculations. At the end we will see how to program summation and product notation in Java or C# language.

What is summation and product notation?

Summation and product are ways of defining mathematical operations that consist of sequences of sums and products respectively.

Imagine that we have to add or multiply all the numbers starting at 1 and ending at 1000, but also multiply each of them by 3.

Using symbology we can write long operations like that in short. In addition the properties can help us to simplify the expression and to calculate the results.

Sigma Notation

In the next video you can see the concept of the sigma notation and an excercise solved using programming techniques in Unity.

The summation is symbolized by the Greek letter Sigma in capital letters.

Below the summation symbol the index variable is indicated and from which value it starts. At the top of the symbol is the last value to be taken by the index.

To the right of the symbol is the expression that determines all the terms of the summation, each term arises from replacing the index in the expression from the first to the last value.

In equation 1 we see on the left side the expression of the summation and on the right side the developed operation.

(1)  

How to program a Summation?

To implement the summation in some programming language is relatively simple, we must define a variable to accumulate the sum that must be initialized in 0 (neutral element for the sum). We have to take into account which numerical set the summands belong to, this will depend on the type of variable to choose.

We define an integer variable for the end of the summation.

We make a for loop that goes from the beginning of the summation to the end and inside the loop we define the operation to make.

In figure 1 we see the implementation of the sum of equation 1 together with the printed result in console.

Fig. 1: Implementation of the summation of equation 1 in Java, Netbeans IDE.

Symbol of Product notación

The product notation is symbolised by the letter Pi in capital letters.

Under the producer symbol is indicated the index variable and from which value it starts. In the upper part of the symbol is indicated the last value that the index will take.

To the right of the symbol is the expression that determines all the terms of the producer, each term arises from replacing the index in the expression from the first to the last value.

In equation 2 we see on the left side the expression of the producer and on the right side the developed operation.

(2)  

Implement the product notation in programming

We must define a variable to accumulate the product that must be initialized in 1 (neutral element of the product). We also analyze the type of numbers we are multiplying to choose the type of the accumulation variable.

We define a whole variable for the end of the producer.

We make a for loop that goes from the beginning of the production to the end and inside the loop we define the operation to be performed.

In figure 2 we see the implementation of the producer of equation 2 together with the printed result in console.

Fig. 2: Implementation of the equation 2 producer in Java, Netbeans IDE.

Introduction

The Cartesian coordinate system is named after the philosopher and mathematician René Descartes, considered the creator of analytical geometry.

This system allows us to represent points on a line, in the plane and in space using arrays of numbers. For example: (1,5), (-3,0), (4,1,-1), etc.

What is a Cartesian plane?

The Cartesian plane is defined by two straight lines perpendicular to each other, one horizontal and one vertical, these straight lines are known as Cartesian axes. Using these axes we can identify any point on the plane with a single ordered pair of numbers.

The horizontal axis is known as the abscissa axis and is usually the x-axis. The vertical axis is known as the ordinate axis and is usually the y-axis.

The point where the abscissa and ordinate axes are cut is known as coordinate origin or simply origin and is the point (0.0).

The following figure shows a Cartesian plane with the point (2,1) plotted.

Fig. 1: Plano cartesiano xy con el punto (2,1) representado.

Quadrants of the Cartesian plane

Quadrants are characteristic regions of the plane defined by changes in signs on coordinate axes.

There are four quadrants, the first is the upper right region and they are listed counterclockwise.

Fig. 2: Identification of the quadrants of the Cartesian plane.

As shown in figure 2, quadrants are defined in the following regions.

First quadrant: { x > 0 , y > 0 }

Second quadrant: { x < 0 , y > 0 }

Third quadrant: { x < 0 , y < 0 }

Fourth quadrant: { x > 0 , y < 0 }

Representation of functions in the Cartesian plane

The Cartesian plane also serves to represent functions, i.e. rules that assign each point of the x-axis to a point of the y-axis. Figures 3 to 6 show some examples of function graphics in the Cartesian plane.

Fig. 3: Graph of a linear function.
Fig. 5: Graph of a cubic function.
Fig. 4: Graph of a quadratic or parabola function.
Fig. 6: Graph of a sine function of x.

Cartesian system in Unity

Cartesian coordinates are used in various places in Unity, for example to define the position of a GameObject in the plane or space. But for the purpose I wanted to make a simple function plotter using spheres that move on the x-axis and their position on the y-axis is calculated using the expression of the function.

The buttons allow us to change the expression of the function

Fig. 7: The spheres move according to a linear function.
Fig. 9: The spheres move according to a quadratic function.

Fig. 8: The spheres move according to a sinusoidal function.
Fig. 10: The spheres move according to a sinusoidal function in one section and a linear function in another.

Conclusion

Rectangular coordinates are often used in Unity.

Understanding how the Cartesian plane is used to represent points and functions in the plane, along with knowledge of analytical geometry can help us create new and interesting solutions.

Exit mobile version
Secured By miniOrange