Sunday, 21 August 2016

Thinking in Algorithms

An algorithm is a step-by-step process. This lends itself to being written in an imperative programming language like C#, which executes operations one at a time and in order.
Algorithms are written with statements starting at a beginning statement and finishing that statement before moving on to the next. Just because we know what an algorithm is doesn’t mean it’s any easier to create one.
Therefore, how do we go about writing the all-important algorithm? The first thing should be how you might accomplish any given task by hand. As an example, say we’re a computer surrounded by a mob of zombies.
Thankfully, computers are very fast so we can do a lot before the zombies can get to us.
With this in mind we’re going to want to focus on the zombie closest to us.
Unfortunately, computers are also very dumb, so there’s nothing which allows us to just guess at which one is the closest. First, we’re going to need to know how far away every zombie is from our point of view.
Therefore, the computer would probably start with measuring the distance from itself to every zombie available to make a measurement to. After that we’re going to have to compare zombies and distances, so we’ll start with the first zombie we found and compare its distance to the next zombie we found.
If the next zombie is closer we’ll have to remember that one as being the closest one we’ve come across. Otherwise, if the next one is farther away, then we can forget about him and move on to the next zombie and compare numbers again.
Once we’ve gone through all of the zombies, we should have identified the zombie who is the closest one to us. The process which we just thought through is an algorithm for finding the zombie closest to us. It’s not complex, but we had to do a few steps to get to it. First, we needed to get a list of all the zombies we needed to sort through.
After that it was an iterative process, by which we needed to remember one zombie as the closest one, then compare others against him to decide whether or not he would retain the status of being the zombie nearest to us. We’ll be going over many of these problem-solving thought processes as we learn how to program. This algorithm would look something like the following code block:
void Update () 
{
float closestDistance = Mathf.Infinity;
GameObject closestGameObject = null;
GameObject[] allObjects = (GameObject[]) GameObject.FindSceneObjectsOfType( typeof(GameObject));
foreach(GameObject g in allObjects)
{
if (g.name != this.name)
{  
float distance = (g.transform.position - this. transform. position).sqrMagnitude;  
if(distance < closestDistance)
{   
closestDistance = distance;   
closestGameObject = g; 
 } 
}
}
Debug.DrawLine(this.transform.position, closestGameObject.transform.position); 
}
We won’t cover the entirety of how this code works, as we are yet to discuss the bulk of what’s going on here, but in short we are indeed creating a list of objects called allObjects. Then we enter a loop where we compare the distance of each object against the one we’ve decided was the closest. If we find a closer object then we change the closestGameObject to the compared object. Just for a proof of concept we draw a line from the object. Because the script is attached to the object, we draw a line from the object the script is attached to toward the object selected as the closest.


 Programming is a lot more about a thought process than it is about processing. In other words,  programming is less about how to do multiplication as it is about what to do with the result of a multiplication process. In your everyday life we take for granted the everyday things we do on a regular basis. However, take a moment and really consider the complexity involved with something as simple as breathing.
Your diaphragm is receiving signals from your autonomic nervous system, causing several chemical reactions in the diaphgragm’s muscle tissue, which then pull proteins toward one another causing it to contract. This in turn creates a lowered air pressure in your lungs, which pulls in air.
There’s a whole number of chemical processes which then allow the oxygen in the atmosphere to enter your blood stream. Thankfully, all of this happens without our thinking of it because of chemistry and physics. In programming, nothing is so automatic.




No comments :

Statements and Expressions

When reading a book or story you extract meaning from an ordered chain of words.
In a similar way, computers extract commands from a chain of ordered instructions.
In English we call this a sentence; programmers call this a statement.

A statement is considered to be any chunk of code which accomplishes some sort of task separated by a semicolon. At the center of any given task is the algorithm, not to be confused with a logarithm.
An algorithm is a systematic process that accomplishes something. In many ways you can think of it as a recipe, or rather a recipe is an algorithm for making food.
It can take just one or two statements to accomplish a task, or it could take many hundreds of statements.

This all depends on the difficulty of a given task. Each individual statement is a step toward a goal. This is the difference between spending a few minutes frying an egg, or spending an hour baking a souffle. Each step is usually fairly simple; it’s the final result that matters.
Like sentences, statements have different forms. Statements can declare and assign values to variables. These are called declaration and assignment statements. These statements are used to set up various types of data and give them names.

Expressions The subjects of your statements are called identifiers. An assignment statement is used to give an identifier a value. When you read “Jack is a boy and Jill is a girl,” you’ve mentally assigned two subjects their genders. In C# this might look more like:
gender Jack = male; gender Jill = female;
Assignment statements often incorporate some sort of operation.
These are called expressive statements. Different from expressing an emotion, expressions in code look more like “x + y.” Expressions process data. After processing, the result of an expression can be assigned to a variable.

A collection of statements is called a code block, not like a roadblock which might stop your code, but more like a building block, anything that’s used to build.
When writing a story, we call a collection of sentences a paragraph. The statements in a block of code work with each other to accomplish a task.
No comments :

Compiling: Turning Words into Computer Instruction

Once your source code is finished, it is time to compile. Compiling is the process of taking all of your source files and building bytecode.
Unity 3D (Game Engine) uses Mono, as it is a compiler to generate the bytecode, but Unity 3D does this automatically. Mono is an open-source compiler that runs on many different processors and operating systems. The combination of central processing unit (CPU) and operating system is often called a platform.

Each platform requires a unique native machine code to execute or run. Building code for each platform is called a target. Unity 3D converts the bytecode into a native machine code and can target Mac, PC, Android, and iOS.

Native machine code is the set of instructions that directly talk to the CPU and operating system. Unity 3D is a simple way to generate the complex set of instructions for your computer to run.
Code that talks directly to the hardware is referred to as “low-level” programming.
There are layers of software between you and the computer’s hardware.
When writing C# for games using Unity 3D, your code is compiled by Mono.
Unity 3D then takes the bytecode from Mono and com- piles for a target platform into a native machine code.

Both Unity 3D and Mono are the layers underneath your code and the computer’s hardware putting you on a higher level. This is often referred to as a computer layer abstraction.
That is why C# is usually considered a high-level programming language.
Programming at a lower level requires much more knowledge of memory management and a wide variety of other APIs that might include graphic cards, physics, sound, and everything else that runs a game.

Writing for a layer involves an in-depth knowledge of both the layers below and above the one you’re writing for.
The computer hardware, such as CPU, graphics card, memory, and storage, live on the lowest level. Above them is the basic input/output system (BIOS) and software that starts the hardware when you press the Power button.

Above that is your computer’s operating system and drivers that talk to the hardware. Finally, Unity 3D lives above the operating system, and then your code lives above Unity 3D.
That is why we’re going to use Unity 3D to write games, and not starting from scratch in raw C++. Otherwise we’ll have to spend a few years learning about physics, rendering, and assembly language, or the instruction set that your CPU uses to think.
No comments :

Learning to Copy and Paste

“A good artist creates, a great artist steals.” There are code examples for you to copy and paste into your project. The content of this book and all downloadable content are no different. This means that you’ll have to understand what the code is doing to interpret it to fit your needs.
Every programmer does this habitually.
 
It is important to learn how to do this since it is something that you actually need to do in many cases not only to learn but also to get any unfamiliar task done. Programming is a constant learning process. It is a language to command computers.
Anytime you learn a new language, there will be plenty of words which you’ll have to look up.
Add to this the fact that every programmer gets to make up new words, and you’ve got a language that you’ll always need a dictionary for.

When some code is shown, you’ll be expected to copy that code into your project. With your fingers ready on the keyboard, you’ll want to get in the habit of typing.
There is a reason why programmers are usually fast typists. This is also cause for programmers to be picky about what keyboard they prefer. In most cases, the projects in this book will be in some state where you can read text that is already in place.

Most of the projects are in a more complete state, where you’ll be able to run them and see an intended result. As a programmer I’ve gotten used to searching the Internet for example code.
Once I’ve discovered something that looks useful, I copy that code and paste it into a simple test case. After I’ve wrapped my head around what the code is doing, I rewrite it in a form that is more suited for my specific case.
Even if the code involves some fun trick, I’ll learn from that code.
As I learn new tricks, I grow as a programmer. The only way to learn new tricks is to find the necessity to solve a new problem for which I haven’t already figured out a solution. Finding solutions to problems is a fundamental part of being a programmer.
No comments :

What Is Programming?

It’s all about writing code. Programming is a process in which we organize data and use logic to do something with those data. The data are everything a computer can store; they can range from numbers to zombie characters in a video game.

You do this by writing text into files called source code. Source code written into text files replaces punch cards used by the computing machines half a century ago.
When data are combined with logic and then written into a single file, they’re called a class. Classes are also data, and as such can be managed with more logic.
Classes are used to create objects in the computer’s memory and can be duplicated to have a life of their own. Classes are used to build objects. Each piece of data within the class becomes a part of that object. Different chunks of data inside of a class are called class members.
Class members can also be chunks of logic called functions or methods. In a game with a horde of zombies, each zombie is duplicated or instanced from a zombie class. Each zombie has unique values for each attribute or data element in the class.

This means hit points, and locations are unique for each duplicate zombie object. Objects created from a class are called instances. Similar to families, objects can inherit properties from one another. The child sometimes called a subclass inherits attributes from its parent. For instance, the child created from a zombie may inherit the parent’s hunger for brains.
To be useful, the child zombie can also add new objects and change the objects it inherited from its parent class. As a result, now the child zombie might have tentacles that the parent didn’t have. Objects talk to each other through events and messages.

Shooting at zombies can create an event, or in programmer terms, it “raises” an event. The bullet impact event tells the zombie class to then take necessary steps when hit by a bullet.
Events command the class to take actions on its data, which is where functions come in.
Functions, also known as methods, are sections of logic that act on data. They allow your class to cre- ate additional events and talk to yet more objects.
As the player presses the trigger and moves the joystick around, yet more events can be raised and messages can be sent. Events and messages allow the player to interact with your world; logic events and objects together build your game.
No comments :

Floating Point


Floating point numbers have been a focus of computers for many years. Gaining floating point accuracy was the goal of many early computer scientists. Because there are an infinite possibilities of how many numbers can follow a decimal point, it’s impossible to truly represent any fraction completely using binary computing. A common example is Ï€, which we call pi. It’s assumed that there are an endless number of digits fol- lowing 3.14. Even today computers are set loose to calculate the hundreds of billions of digits beyond the decimal point. Computers set aside some of the bits of a floating point number aside to represent where the decimal appears in the number, but even this is limited. The first bit is usually the sign bit, setting the negative or positive range of the number. The following 8 bits is the exponent for the number called a mantissa. The remaining bits are the rest of the number appearing around the decimal point. A float value can move the decimal 38 digits in either direction, but it’s limited to the values it’s able to store. We will go further into how numbers are actually stored in terms of 1s and 0s in Section 8.9. For now just understand that numbers can represent only a limited number of digits. Without special consider- ations, computers are not able to handle arbitrarily large numbers. To cast a float into an int, you need to be more explicit. That’s why C# requires you to use the cast and you need to add the (int) in int Zint = (int)Zmove;. The (int) is a cast operator; or rather (type) acts as a converter from the type on the right to the type needed on the left.
No comments :

The Rule of Three

The Rule of Three is a simple idea that any time you need to do any given task more than three times it would be better served by creating a new single procedure to accomplish the task that has been done manually. This reduces the chance of error in writing the same code more than three times.
This also means that changing the procedure can be done in one place.
void CreateANamedObject (PrimitiveType pt, string n, Vector3 p) 
{
GameObject g = GameObject.CreatePrimitive(pt);
g.name = n; g.transform.position = p;
}
We take the code that’s repeated and move it into a function. We then take the values that change between each iteration and change it into a parameter. In general, it’s best to put the parameters in the same order in which they’re used. This isn’t required, but it looks more acceptable to a programmer’s eyes.
void Start () 
{
CreateANamedObject(PrimitiveType.Cube, "MrCube", new Vector3(0,1,0)); 
}
We then test the function at least once before writing any more code than we need to. If this works out, then we’re free to duplicate the line of code to accomplish what we started off doing.
void Start () 
{
CreateANamedObject(PrimitiveType.Cube, "MrCube", new Vector3(0,1,0)); CreateANamedObject(PrimitiveType.Cube, "MrsCube", new Vector3(0,2,0)); CreateANamedObject(PrimitiveType.Cube, "MissCube", new Vector3(0,3,0)); CreateANamedObject(PrimitiveType.Cube, "CubeJr", new Vector3(0,4,0)); 
}
Again, though, we’re seeing a great deal of duplicated work. We’ve used arrays earlier, and this is as good a time as any to use them. By observation, the main thing that is changing here is the name. Therefore, we’ll need to add each name to an array.
string[] names = new string[] {"MrCube", "MrsCube", "MissCube", "CubeJr"};
The variable declaration needs to change a little bit for an array. First of all, rather than using type identifier;, a pair of square brackets are used after the type. The statement starts with string[] rather than string. This is followed by the usual identifier we’re going to use to store the array of strings. Unlike an integer type, there’s no default value that can be added in for this array of strings. To com- plete the statement, we need to add in the data before the end of the statement. The new keyword is used to indicate that a new array is going to be used. The array is a special class that is built into C#. Therefore, it has some special abilities that we’ll get into later. Now that we’ve declared an array of names, we’ll need to use them.
 
No comments :

Null Is Not Void

There is conceptual difference between void, which is nothing, and null, which is more like not  something. The word void means there is no intention of anything to be presented, whereas null implies that there can be something. We may add if(target != null) and can say that target can be empty or it can be Zombie. When target isn’t a zombie, target is null; when it is there, it’s Zombie.

We may add if(target != null)—in more readable English, “if the target is not null”—and then conditionally execute the following code block. In the case where we have a target, we can draw a line from the camera’s transform.position to the target’s transform.position. This code alleviate the error, and thus we don’t have to worry about sending Draw.DebugLine an error-inducing null reference.
No comments :

Static,Static Variables,Static Functions

Static 
The static keyword is a keyword that ties all instances of a class together. This allows all instances of a class to share a common variable or function. When you see static next to a function, this means you don’t need to make a new instance of the class to use it. Because static functions and variables are class-wide, we access them in a slightly different way than an instance of a variable or function. There is a static function found inside of Input called GetKey(), which we will use. The last keyword is bool, after public and static. We’ve seen bool before, but this is used as a return type. When we write our own functions, we’ll also include our own return type, but just so you know, return types are not limited to bool. Functions can return any data type, and now we’ll take a look at how this all works.
A Basic Example 
Let’s start with the Static project; begin by opening the scene in the Unity 3D Assets Directory. The Main Camera in the scene should have the Player component attached.
using UnityEngine; 
using System.Collections;
 public class Player : MonoBehaviour
{
//Use this for initialization
void Start ()
{
}

//Update is called once per frame
void Update ()

//add in a check for the A key  bool AKey = Input.GetKey(KeyCode.A); 
if (AKey) 
{  
Debug.Log("AKey");
 }
}
The code here will send the following to the Console panel in Unity 3D.
AKey UnityEngine.Debug:Log(Object) Player:Update () (at Assets/Player.cs:15)
The KeyCode class has a public variable for each key on your computer’s keyboard. Each variable returns true when the key on the keyboard is pressed. The Input.GetKey() function returns the bool value based on which the key is checked in the KeyCode class. We assign the bool AKey to the returned value from the Input.GetKey(KeyCode.A); function. The statement if (AKey) then executes the Debug.Log("AKey"); which then prints out AKey to the Unity Console window. The GetKey() function is a member of the Input class and is accessed by using the . or dot operator. Now that we’re reading libraries we need to know how to get to the members of the classes we’re looking at.

 //image

Select the GetKey() and go to the definition of this function. You can do this by right clicking on the word and selecting Go To Definition in the pop-up. This will open the Assembly Browser, where we’ll be shown the function’s definition. We’re shown public static bool GetKey(KeyCode key) as the function’s definition. This process provides us with the beginnings of a player controller script. Filling in the rest of the WASD keys on the keyboard will allow you to log the rest of the most common movement keys on your keyboard. The Input class is found in UnityEngine that was included in this class with the using UnityEngine directive at the top of the class.

From previous chapter lessons, you might imagine we’d need to create an instance of Input to make use of its member functions or fields.
This might look like the following:
void Update () 
{
Input MyInput = new Input();
bool AKey = MyInput.GetKey(KeyCode.A);
Debug.Log(AKey); 
}
While this syntactically makes sense, you’re better off not creating new instances of the Input class. The GetKey() function is static, so there’s no need to create an instance of Input to use the function. This will make more sense once we write our own static function later in this chapter. However, should we actually try to use MyInput as an object, we’d have some problems.


 //image



When we check for any functions in the MyInput object after it’s been instanced, we won’t find any- thing useful. The only things available are universal among all things inheriting from the object class. We’ll get to what the object class is in Section 6.13.4, about inheritance, but for now, just assume that these functions will appear and act the same for pretty much anything you are allowed to make an instance of. The lack of functions or variables is due to the fact that all of the functions and variables have been marked as static, so they’re inaccessible through an instance of Input. Statically marked functions and variables become inaccessible through an instance. This inaccessibility is related to an object’s interface and encapsulation. This doesn’t mean that they are completely inaccessible, however; but to see them, we’ll need to write our own class with our own functions and variables.

Static Variables 
Let’s start off with a simple concept: a static variable. Using our previous analogy of toasters, each new toaster built in a factory has a unique identity. Each unit built would have a different serial number. Once in someone’s house, the number of times the toasters have been used, when they are turned on and begin to toast, and their location in the world are all unique to each toaster. What they all share is the total number of toasters that exist. The static keyword means that the function or variable is global to the class it’s declared in. Let’s make this clear; by declaring a variable as static, as in static int i;, you’re indicating that you want to use the int i without needing to make an instance of the class that the variable is found in.

Variables that are unique to each instance of a class are called instance variables. All instances of the class will share the static variable’s value regardless of their instanced values. If we create a mob of zombies, we might find it important to maintain a certain number of zom- bies. Too many and the computer will have problems keeping up. Too few and the player will go around with nothing to shoot at. To give ourselves an easier time, we can give each zombie a tele- pathic connection with all other zombies. A programmer would call this a static variable or a static function. As we’ve seen, variables usually live a short and isolated life. For instance, the variable used in the ever-powerful for loop exists only within the for loop’s code block. Once the loop is done, the variable in the for loop is no longer used and can’t be accessed outside of the loop.

for (int i = 0; i < 10; i++) 
{
print(i);//prints 1 to 10
} //i no longer exists 
print(i);//error, i is undefined

Now that we’re creating objects based on classes, we need to make those classes interact with one another in a more convenient way. To keep track of the number of undead zombies in a scene, we could have the player keep track; as each zombie is created or destroyed, a message could be sent to the player. The Player class keeping track of important zombie data is awkward. Zombie-related data should remain in the zombie class, unrelated classes should not depend on one another in this way. The more spread out your code gets, the more problems you’ll have debugging the code.
Creating self- contained classes is important, and prevents a web of interdependent code, sometimes referred to as spaghetti code. Remember that when an object is created it’s instanced from a single original blueprint, which can include some variables that are shared between each instance of the class. With static variables instanced cases can talk to the blueprint for a common connection between any new instances made from it.

Static Functions 
Static functions act on behalf of all instances of the class they are a member of. They work only with static variables of the class. If we extend our zombie class with a new static function, we can use the zombie
class to call a static function that can read static variables. To make the static function accessible to other classes we need to make the static function public as well.

using UnityEngine; 
using System.Collections;
public class Zombie : MonoBehaviour
{
static int numZombies; //int numZombies;//no longer static

//Use this for initialization
void Start ()

numZombies++; 
Debug.Log(numZombies);
}
//Logs number of zombies to the console
public static void CountZombies()
 { 
Debug.Log(numZombies);
}

Then we’ll add a call to Zombie.CountZombies(); to find out how many zombies have been created in the Update () function of the Player class, by adding it to the if(AKey) code block.

using UnityEngine; 
using System.Collections; 
public class Player : MonoBehaviour
{
 //Use this for initialization
void Start ()
{
}
//Update is called once per frame
void Update ()

//add in a check for the A key  bool AKey = Input.GetKey(KeyCode.A);
 if (AKey) 
{  
Debug.Log("AKey");   //calls the static function in Zombie  
Zombie.CountZombies();
 }
}

Now when the A key on the keyboard is pressed, we’ll get a count printed to the Console panel indicating the number of zombies in the scene along with the Debug.Log("AKey"); console log.

//image

The 4 being printed out comes from the public static void CountZombies(); function call being made to Zombie, not from any of the instances of the zombie class attached to the capsules in the scene. To call static functions, you use the class name, not the name of an instanced object made from the zombie class. As you can see, there’s more than one way the class identifier is used. Up to this point, we’ve been using the class name mostly as a way to create an instance of that class. With a static function or variable, the class identifier is used to access that static member of the class.



No comments :

Wednesday, 10 August 2016

Type Casting, Numbers

This is a simple exercise, but an important one nonetheless. When you start to deal with keeping score, or recording injuries to a monster, it’s important that behaviors are predictable. Many problems begin to show up if the math you’re using involves mixing numbers with decimal values like floats or doubles, or with integers which have no decimal value.
int i = 100;
Decimals are not allowed on an int value.
float f = 100.0f;
double d = 100.0;
Decimals are allowed for both float and double. The only caveat is that a float requires an f post fixed to the number when it’s assigned.
Converting types between one another is pretty simple when you need to deal with numbers. When we start creating our own classes the task of casting becomes a bit more detailed, but not necessarily more difficult; there’s just a bit more work involved. We’ll get to that soon enough.
When we go between number types or the built-in value types (POD), we work with things which seem to come with C#. So far we’ve seen things like int and float. Integer values like 1, 7, and 19 are useful for counting. We use these for counting numbers of items in an array, or how many zombies are in a scene, for instance. Integers are whole numbers, even though we might be counting zombies whole or not.
Once we start needing numbers with fractions we need to use float values. To get an object’s speed or x, y, and z coordinates in space we need to use values like 12.612f, or x = 13.33f, to accurately place an object in space. If not, objects would move around in a scene as though they were chess pieces locked to a grid.
When a float value exists as 0.9f we lose some values after the decimal when converting the floating point value to an integer.
void Start ()
{
float a = 0.9f;
int b = (int)a;
Debug.Log(b);
}
If we use the above code in a new script called Casting.cs attached to the Main Camera in a new Unity 3D project we’ll get the following output to the Console panel.
0
UnityEngine.Debug:Log(Object)
Casting:Start ()  (at Assets/Casting.cs:10)
Without the cast operator int b = a; we get an error telling us we need to cast the value before assigning it.
Assets/Casting.cs(9,21): error CS0266: Cannot implicitly convert type ‛float’ to ‛int’.
An explicit conversion exists (are you missing a cast?)

The first part of the error message says “Cannot implicitly convert type,” which has a very specific meaning that we’ll get to before the end of this chapter, but first let’s cover explicit type casting.

Explicit versus Implicit Casting
As we have seen, in the Start () function where we declared float a = 0.9f; a was converted to 0. Even though we were only 0.1f away from 1 and 0.9f away from 0 we’re left with a 0 instead assigned to int b. To do these conversions we use the explicit casting method, as shown with (int)a;, which explicitly tells C# to convert the value stored at a to a float value. When we are required to use an explicit cast, we’re also warned that there may be some data lost in the conversion.
Casting is a process by which C# changes the type of a variable to another type. This may or may not involve a loss of information. In some cases, the conversion doesn’t require the explicit cast operator. The following code casts an int to a float.
int c = 3;
float d = c;
Debug.Log(d);
With the above code we get a 3 printed out to the Console panel. We didn’t need to use an explicit casting operator. This is because when we cast from an int, in this case 3, there would be no data loss when it’s cast to a float. This is possible through an implicit cast. Implicit casts are allowed only when there is no data lost in the process of converting from one type to another.
There are no integer values which will result in a loss of any value when it’s converted to a float. Technically, there are more float numbers between 0 and 1 than there are integer numbers between 0 and 1, or any other sequence of two numbers for that matter.

A Basic Example
Create a new project called NumberTypes and assign a C# script to the Main Camera called NumberTypes.cs. In the Start () function include the following code.
void Start ()
{
int a = 1;
double b = 0.9;
int c = a * b;
Debug.Log (c);
}
If we look at what is going on here we’ll want to think for a moment about what it means. The integer a is set to 1 and double b has 0.9 assigned. We should assume that 0.9 will be assigned to c after the multiplication, but this assignment is stopped by a type conversion error. C# usually gives us pretty clear reasons for its errors. In this case we know there’s a cast missing between an int and a double.
Assets/NumberTypes.cs(10,21): error CS0266: Cannot implicitly convert type ‛double’ to ‛int’. An explicit conversion exists (are you missing a cast?)
The error states we can’t implicitly convert a double to an int; why not? 1 certainly looks like 1.0, or so it seems. However, 0.9 can’t be turned into an integer. There’s no integer between 0 and 1. Even though 0.9 is very close to being 1, it’s not.
int c = a * (int)b;
We use type conversion to tell C# to explicitly change b from a double to an int by preceding the b with (int). What value is going to be assigned to c if it can’t be 0.9? The (int) operator is an explicit cast.
0
UnityEngine.Debug:Log(Object)
NumberTypes:Start () (at Assets/NumberTypes.cs:11)
0 is less than 0.9; we’ve lost data going from the double value to an integer value. Even though 0.9 is almost a 1, the first int value is 0, followed by values that are cut off by the type conversion. This is why type conversion matters.
We will find other casts which look like this in Sections 6.14 and 6.20, but we’re introducing the concept early on as it’s a very common problem to come across. The syntax (int) turns a number following this operator into an int.
Likewise
int i = 0; double d = (double) i ;
 is a way to cast an int into a double. However, this isn’t always necessary.
Some conversions take place automatically as an implicit cast. In the above example we can use the following code without any problems.
void Start ()
{
int a = 1;
double b = 0.9;
int c = a * (int)b;
Debug.Log (c);
double d = a;
Debug.Log(d);
}
Here we assign double d = a; where a is int 1, which we know isn’t a double. This produces no errors. The same goes if we add another line float f = a;. In this case f is a float. These are called implicit casts. An integer value doesn’t have a mantissa or an exponent. Both the double and float do have these two possibly large and important values. These two terms were explained at the end of Chapter 2.
When mashing a double into an int we lose the mantissa and exponent. By using an explicit cast, we tell C# that we don’t mind losing the data. This doesn’t mean that an implicit cast will not lose any data either. An int can hold more significant values than a float. We can observe this with the following lines of code added to the Start () function.
Debug.Log(largeInt);
float largeFloat = largeInt;
Debug.Log(largeFloat);
int backAgain = (int)largeFloat;
Debug.Log(backAgain);
This code produces the following console output, after a bit of cleaning up:
2147483647
2.147484E+09
-2147483648
When we start with the value 2147483647 assigned to int we’re at one extreme of the integer value. This is the biggest number the int can hold, for reasons discussed in Section 3.11.1, but in short, it’s because it’s using only 32 bits to store this number.
If we cast this into largeFloat we can use an implicit cast, which converts the value from int to float. In this case we see only 2.147484 followed by the exponent E+09, which tells us that the dot (.) is actually nine places over to the right.
When we convert the float back into an int with an explicit cast we get a −2147483648, which is certainly not what we started with. This tells that there’s some significant information lost in the conversion from float to int, but there were also numbers lost in the implicit cast from int to float.
This still happens if we remove a digit from the end.
int largeInt = 214748361;//cutting off a digit and ending in 1
Debug.Log(largeInt);
float largeFloat = largeInt;
Debug.Log(largeFloat);
int backAgain = (int)largeFloat;
Debug.Log(backAgain);
This sends the following numbers to the console:
214748361
2.147484E+08
214748368
The last digit is changed from 1 to 8. The 8 is coming from some strange conversion when we go from int into float. Even if we look at the numbers being stored in the float value we can tell that there’s already a change in value. This tells us that in general, we need to be very careful when converting from one type into another.
Logically, another difficult problem is converting from a string to a number value. When you use string s = "1"; you’re not able to use (int)s to convert from a string to an int. The types of data are very different since strings can also contain letters and symbols. The conversion of (int) "five" has no meaning to the computer. There’s no dictionary which is built into C# to make this conversion.
This doesn’t mean that there are no options.
string s = "1";
int fromString = int.Parse(s);
Debug.Log(fromString);
The code added to the Start () function will produce the following number:
1
There are plenty of options when faced with dealing with significantly different types. The int.Parse() function is an option that we can use to convert one value into another. Again, we might be getting a bit ahead of ourselves, but it’s important to see that there are many different ways to convert between different types.
No comments :

Strong Typing

This has nothing to do with how hard you type on the keyboard! C# sees a difference between numbers in how they are written. A whole number like 1 is different from 1.0, even though we can think of them as having the same value. Some of these differences can be added by adding a letter. Therefore, 1.0 and 1.0f are actually different numbers as well.
C# is a strongly typed programming language. When a programming language uses strong types you’re expected to keep the different types separated. This means that a 1 + 1.0f can create a problem. Because the two numbers are actually different types of numbers we have to convert one of them to match the other before the operation is allowed to take place.
To convert from one type to another we have to tell C# that we intend to make that conversion from a 1 to a 1.0 by using what’s called a cast operator. Aside from changing how memory is used, types also limit any problems which might come about when working in a team of programmers.

If one programmer is new to your game and has made assumptions about hit points being in floating point values, he’d quickly find out as soon as he looked that you’re using integer values and change how he intends to use those numbers. Value types not only store a value assigned to them but also provide a great deal of information to be inferred by the programmer reading the code.
In Unity 3D a Vector3 vec = new Vector3(1.0, 1.0, 1.0); will throw an error. The number 1.0 is called a double, which uses 64 bits, whereas 1.0f, which is a float, uses 32 bits. The difference means float 1.0f is half the size of the double 1.0 in memory. A Vector3 is made up of three float values, not three doubles.
Therefore, in terms of declaring a variable and assigning it float f = 1.0f and double d = 1.0; the same type problems exist as with assigning a Vector3(), which is made of three different float values. To properly tell C# you mean a 32-bit version of 1.0 would be to add an f after the number: 1.0f means you want to use the 32-bit version of 1.0 and not the 64-bit version of 1.0. Therefore, to declare Vector3 vec = new Vector3(1.0f, 1.0f, 1.0f); is the correct way to assign a proper Vector3().
Confused? I’d imagine so; we’ll clear things up in a bit. Just hang in there.
For our purposes of learning how to code, knowing anything about bits may not mean a lot. However, if you ever talk to a programmer it’ll be very important that you know the difference. Before getting too far ahead we should know that Unity 3D uses floats, ints, and doubles quite often. There is also a difference between the different data types and that they cannot be simply used interchangeably without consequence.

 Dynamic Typing

Not all programming languages are so strict with types, but it’s a good to get used to working with strict types before learning a more lazily typed programming languages, like Lua (http://www.lua.org/ ). Type conversion is important for learning more complex languages like C, or C++.
These languages offer a wider number of platforms and a more detailed level of control.
With dynamically typed languages like Lua or UnrealScript, you can run into strange hard-to-track-down bugs. These are sometimes called “Duck”-typed languages; this refers to the proverb “if it looks like a duck and it sounds like a duck, it’s probably a duck.” However, when it comes to a type we might see something like this:
var i = 1;
if (i)
{
Console.writeLine("is it true or a 1?");
i = i * 0.1;
}

In the above it’s not clear what the variable i is supposed to be, is it a bool or an int or a double? When var above starts off as an integer but we use it as a bool and then multiply it by a floating point value, what is i? What have we turned it into if we want to use it as something else, or how do we turn it back?
As we will see in Section 7.14.4, we are allowed to make some exceptions to the type of a variable. The keywords var and dynamic do mean you’re expecting an unexpected type to be coming, but once it’s there, you had better know what to do with it.
No comments :

Types

When we assign a variable a value such as int i = 1; we’re making an interesting assumption.
We assume using 1 automatically infers a value type that matches the variable type.
Computers use a wide variety of different types of data for storing numbers.
So far we’ve been seeing the word int being thrown around as though you know what an int is. In our everyday lives we hardly think there’s any difference between numbers 1 and 1.0 or even the word one. As humans we can easily conceptualize numbers as units of measure and converting between them. The conversion between the word one and the number 1 isn’t so easy for a computer.
The keyword int is short for integer. Integers are whole number values. The integer is a C# built-in type. Basically, this means that integers are a fundamental part of C#.
Other built-in types include float, double, string, bool, and object. Less commonly used built-in types are char, short, and byte. Altogether, there are 15 different built-in types. All of these, except object and string, are value types.
Every type of data you’re able to build must be based on all of these built-in types. The system which creates all of these floats, doubles, and bools is rooted in the origin of computing.
Remember the punch tapes and pieces of paper with holes in them? Those were records of 1s and 0s which were fed into computers for storing in the form of mechanical switches, either on or off. The patterns represented numbers or instructions and logic.
Today, we still use the same system of 1s and 0s, or binary, only we don’t need to punch holes in paper to tell the computer what to do. The methods of creating and storing the instructions have become many times more complex, but nonetheless the principle of the 1 and 0 are the same.
These are called bits; one possible origin for that name is the little bits of paper that were left over from punching all of the holes in the paper cards.

Value and Reference Types
The int, float, double, and bool are commonly used value types. The basics of this usage pattern relate to the system that stores and organizes the computer’s memory. When you talk about computer storage you use the word megabyte or gigabyte. Value types are stored with a very specific purpose in mind: to keep track of a numeric value.
NOTE: The word mega refers to how many millions of bytes a component in your computer can store. Giga indicates how every many billions of bytes are being stored. Have you ever thought about what a byte actually is?
A byte is what is called an 8-bit unsigned integer, or a system of using 8 bits to form a number. What this means is that it’s a whole number like 0, 7, or 32,767. The word unsigned indicates that the number cannot be negative, like −512.
A 1 or 0 in computer terms is called a bit. We won’t go into detail on how computers use bits to count, and it’s a rather fun thing to learn on your own. However, it’s important to know that a byte has a limited range, from 0 to 255. I’ll just leave you with the idea that you could count up to 1023 on your 10 fingers if you used binary rather than decimal. Your fingers can be used to represent a 10-bit unsigned integer.
The computer’s calculation capabilities used to be far more limited than they are today. An 8-bit game console made in the 1980s had a limited number of colors, 256 to be exact. This limitation was based on the number of bits that the processor could handle. The processor had a limited number of transistors which could be used at any one time. Shortly after, floating point coprocessors were introduced, which had a much larger numeric range allowed, by having closer to 32 bits to work with.
In all of these cases, when you use a value type, that number is actually stored as 1s and 0s in your computer’s RAM. This should be considered fairly remarkable. In the past you’d have to go through flaming hoops to store a value.
Now you just type in float f = 3.1415926535; and you can measure the circumference of the universe accurately to within the width of a single atom.
What all of these types have in common is that they are stored as a single element. Large values like double gigawatts = 1210000000.0; and double mint = 2.0; use the same amount of memory.

Your computer doesn’t assign one double or the other more space in memory. These types are referred to as primitive types. The only difference between an int and a float is the number of bits they use at a time, 8 and 32 respectively; doubles use 64 bits.
The string and object types differ a bit in how they are stored. These types are a composite of any number smaller elements. The bigger a string or object the bigger chunk of memory the computer opens up to place that object or string. These are called reference types or sometimes called nullable types because C# doesn’t look to a single element in memory to get data from it.
We will explain nullable types in Section 4.4.1.2, but in short a nullable type is a space in memory which is reserved for data that has yet to be fulfilled. Primitive or value types are commonly reserved and assigned at the same time. There are systems which allow this to be changed, but we’re getting ahead of ourselves for now.
In Unity 3D, a commonly used type is the Vector3. Vectors, in the math world, are directions in x, y, and z with a length. Unity 3D uses vectors to keep track of a position in 3D space. The Vector3 type is a composite of three float variables. This means that a Vector3 is made up of different components. From this, we may infer that a Vector3 is a nullable type. Each float is labeled x, y, and z. However, unlike the primitive types the Vector3 needs to be instanced. This means that you can’t simply use the following syntax.
int i = 0;//a valid initialization of an int.
Vector3 v1 = (x = 0,y = 0,z = 0);//not valid initialization.
Vector3 v2 = new Vector3();//this is how it’s done.

Nullable types need to be initialized; that is, they need some form of initial value. We’ll go into further detail on this later. It’s important to remember there are differences between types when they are being initialized. Later on, as you begin to create and use objects and variables it’ll be important to remember how to initialize the different variable types.
No comments :

Variable Names (What You Should Must Know Before Writing Code!)


It’s important to know that variable identifiers and class identifiers can be pretty much anything. There are some rules to naming anything when programming. Here are some guidelines to help. Long names are more prone to typos, so keep identifiers short. A naming convention for variables should consider the following points.
The variable name should indicate what it’s used for, or at least what you’re going to do with it. This should be obvious, but a variable name shouldn’t be misleading. Or rather, if you’re using a variable named radius, you shouldn’t be using it as a character’s velocity. It’s also helpful if you can pronounce the variable’s name; otherwise you’re likely to have issues when trying to explain your code to another programmer.

int someLong_complex_hardToRememberVariableName;

There is an advantage to keeping names as short as possible but still quite clear. Your computer screen, and most computers for that matter, can only fit so many characters on a single line. You could make the font smaller, but then you run into readability issues when letters get too small. Consider the following function, which requires more than one variable to work.

SomeCleverFunction(TopLeftCorner – SomeThickness + OffsetFromSomePosition, BottomRightCorner – SomeThickness + OffsetFromSomePosition);

The code above uses many long variable names. Because of the length of each variable, the statement takes up multiple lines making a single statement harder to read. We could shorten the variable names, but it’s easy to shorten them too much.

CleverFunc(TL–Thk+Ofst,LR–Thk+Ofst);

Variable names should be descriptive, so you know what you’re going to be using them for: too short and they might lose their meaning.

int a;

While short and easy to remember, it’s hard for anyone else coming in to read your code and know what you’re using the variable a for. This becomes especially difficult when working with other programmers. Variable naming isn’t completely without rules.

int 8;

A variable name can’t be a number. This is bad; numbers have a special place in programming as much of it has other uses for them. MonoDevelop will try to help you spot problems.
A squiggly red line will appear under any problems it spots. And speaking of variable names with numbers, you can use a number as part of a variable name.

int varNumber2;

The above name is perfectly valid, and can be useful, but conversely consider the following.

int 13thInt;

First Steps
Variable names can’t start with any numbers. To be perfectly honest, I’m not sure why this case breaks the compiler, but it does seem to be related to why numbers alone can’t be used as variable names.
int $;
int this-that;
int (^_^);


Most special characters also have meanings, and are reserved for other uses. For instance, in C#, a - is used for subtracting; in this case C# may think you’re trying to subtract that from this. Keywords, you should remember, are also invalid variable names as they already have a special meaning for C#. In MonoDevelop, you might notice that the word this is highlighted, indicating that it’s a keyword. Spaces in the middle of a variable are also invalid.

int Spaces are bad;

Most likely, adding characters that aren’t letters will break the compiler. Only the underscore and letters can be used for identifier names. As fun as it might be to use emoticons for a variable, it would be quite difficult to read when in use with the rest of the code.

int ADifferenceInCase;
int adifferenceincase;


The two variables here are actually different. Case-sensitive languages like C# do pay attention to the case of a character; this goes for everything else when calling things by name. Considering this: A is different from a.

NOTE:
Trained programmers are often taught a variation of naming conventions, which yields easier-to-read code. Much of this is dependent on scope, which we will discuss in Section 4.4.4. There are also conventions which always prefix variable names with an indication of what sort of data is stored by that variable.
As a programmer, you need to consider what a variable should be named. It must be clear to you and anyone else with whom you’ll be sharing your work with. You’ll also be typing your variable name many times, so they should be short and easy to remember and type.
The last character we discuss here is the little strange @ or at. The @ can be used only if it’s the first character in a variable’s name.

int @home;
int noone@home;


In the second variable declared here we’ll get an error. Some of these less regular characters are easy to spot in your code. When you have a long list of variables it’s sometimes best to make them stand out visually. Some classically trained programmers like to use an underscore to indicate a class scope variable. The underscore is omitted in variables which exist only within a function.
You would find the reason for the odd rule regarding @ when you use int, which is reserved as a keyword. You’re allowed to use int @int, after which you can assign @int any integer value. However, many programmers tend to use MyInt, mInt, or _int instead of @int based on their programming upbringing.

Good programmers will spend a great deal of time coming up with useful names for their variables and functions. Coming up with short descriptive names takes some getting used to, but here are some useful tips. Variables are often named using nouns or adjectives as they describe an attribute related to what they’re used for.

A human character can often have a health attribute.
Naming this HealthPoints or NumberOfHealthPoints is sometimes considered too wordy, or even redundant. However, if you and your friends are accustomed to paper role-playing games then perhaps HitPoints would be preferred.
In the end once you start using the name of the variable throughout the rest of your code, it becomes harder to change it as it will need to be changed everywhere it’s used. Doing a global change is called refactoring, and this happens so often that there is software available to help you “refactor” class, variable, and function names.

NOTE: You may also notice the pattern in which uppercase and lowercase letters are used.
This is referred to as either BumpyCase or CamelCase. Sometimes, the leading letter is lowercase, in which case it will look like headlessCamelCase rather than NormalCamelCase.
Many long debates arise between programmers as to which is correct, but in the end either one will do. Because C# is case sensitive, you and anyone helping you should agree whether or not to use a leading uppercase letter.
These differences usually come from where a person learned how to write software or who taught that person. The use of intermixed uppercase and lowercase is a part of programming style.
Style also includes how white space is used.
When you name variables in Unity 3D the use of CamelCase or BumpyCase will automatically separate the different words indicated by an uppercase letter in the Inspector panel.
This doesn’t actually affect how the declaration was written. This will only change how your variable’s name appears in the Unity 3D editor.


No comments :