Pages

Sunday, March 29, 2015

How To Use Editor Window To Make Custom Editors In Unity (With Sample code)

Hello, readers. Firstly, sorry for such a late post, I was busy for some months as my exams were going on and I had to Prepare for that. As the title says I will give you some information or hints about how to use The Editor Window class in unity to create your custom Editors.

Editor Window
A major strength of unity is to edit or customize or add new features to your workspace that fits your style or your needs. Unity does open the opportunity to do so with editor or editor window class. The Editor Window class enables you to create a custom window that can float free or be docked as a tab, just like the native windows in the Unity interface.

Creating Editor Window
You just need to make a class deriving from the Editor Window class and add a default method Init. e.g. - (You also need to add using UnityEditor; above class declaration to make unity recognize The EditorWindow class).

public class CustomWindow : EditorWindow 
{
[MenuItem("MyMenu/CustomWindow")]
static void Init () 
  {

  }
}


The MenuItem property specify the Menu item for making the window Appear. I've made a menu called MyMenu and a item named CustomWindow in it.
Now You need to add this line in Init method to make the window appear when clicked on the menu item. -

 static void Init ()
CustomWindow window = (CustomWindow)EditorWindow.GetWindow(typeof(CustomWindow));
}

Now save the script and when the compiling is finished in unity You will see your new Menu Item and when you click it you get a clear window which can be tabbed, docked etc.


Now, to add Something to it we need to add another method OnGUI inside your class like this -

void OnGUI () {

}

In this method, you can add buttons, labels, textfields etc. via GUILayout or EditorGUI (or EditorGUILayout) Class. Example -

void OnGUI () {
     GUILayout.Label("Example Text");
        if(GUILayout.Button("Example Button")){
            //Here you can add the code to run when button is clicked
        }
}

Now here is an example of a float field

private float val; //declare this in in class above all methods
void OnGUI()
    {
        GUILayout.Label("Example Text");
        if(GUILayout.Button("Example Button")){
            //Here you can add the code to run when button is clicked
        }  
        val = EditorGUILayout.FloatField("Example float input:", val);
    }


And finally here is the preview of our Editor Window in Action - 



OK The appearance is Fine But How about It's functioning 

Now we know how to add buttons, labels etc. in window about what to do with them i.e. How to make the function the task for which it's created. For that, We will have to first know what is the cause of making an editor window. 
Sometimes developers made them to make their work easier and faster, It's also used commercially to make plugins for unity etc.
To make use of Editor Window you can use any of unity classes to make the window do something freely. But I will show you how to achieve some basic uses of Custom Editors. -

1. Spawning GameObjects or Prefabs - You can use the Object.Instantiate to spawn or clone a game object in the current scene like this - 

 if(GUILayout.Button("Example Button")){
            GameObject obj = Instantiate(GameObject.Find("Cube"));
        }
  

But you need to use the "AssetDatabase.LoadAssetAtPath" function to get the instance of the prefab, then you can use the normal instantiate function. But as the prefab is type of 'object' class to instantiate it, you need to cast it to GameObject in order to spawn it in the current scene. -

 if(GUILayout.Button("Example Button")){
Object Prefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/sphere.prefab", typeof(GameObject));
            GameObject obj = Instantiate(Prefab) as GameObject;
}
    
Note - You need to enter the full path of the Prefab. Like in the example above the prefab named "sphere" should be located in a folder named "Prefabs" and if it's not there it will throw an exception if the prefab is not found in given path.

2.Adding Components to Existing or new GameObjects - To add new components you can use GameObject.AddComponent to add new components to an object. Example -

 if (GUILayout.Button("Example Button"))
        {
            GameObject obj = Instantiate(GameObject.Find("Cube"));
            BoxCollider collider;
            collider = obj.AddComponent<BoxCollider>();
        }  

3.Raycasting Through Mouse position in the Scene View - This is used many times when creating custom plugins for unity or for any other purpose.
To achieve this We will use the -

OnSceneGUI function - This function lets the editor script handle events in scene view. As you should know that The Input class only works in real game not in editor. The inputs through keyboard and mouse are handled with "Event" class. According To Manual - In the OnSceneGUI you can do eg. mesh editing, terrain painting or advanced gizmos If call Event.current.Use(), the event will be "eaten" by the editor and not be used by the scene view itself.

(i) That's Good But How To Use It ?
First add The OnSceneGUI function with its default argument Scene View like this - 

 void OnSceneGUI(SceneView scene){
}

But adding this won't work, you need to add a delegate of OnSceneGUI function to be able to use it. For That Add these -

 void OnEnable()
    {
        SceneView.onSceneGUIDelegate += this.OnSceneGUI;
     }
    void OnDisable()
    {
       SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
    }

We added the delegate for our function when the Window is Enabled and removed the delegate when the window is closed to make it efficient.

(ii) Okay, now how about the raycasting?
To do raycasting through mouse we will use the "Event.current.mousePosition" to get the current mouse position and then cast a ray through it to get the point in space where the mouse is pointing at. code - 

 void OnSceneGUI(SceneView scene)

    {
            if (Event.current.type == EventType.mouseDown)
            {

                Ray grow = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(grow, out hit, 1000))
                {
                    Debug.Log(hit.point);
                }
            }
      }

Preview - 

Now you can Test your script. You may notice that raycasting does fine but when you click in the scene the object in front of it also get selected. It is no problem for us in this script but it may give problem when making something selected. So to prevent unity from selecting or deselecting objects, we need to add this line in OnSceneGUI -
 HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

So the script now look like this - 

  void OnSceneGUI(SceneView scene)
    {

  HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));            if (Event.current.type == EventType.mouseDown)
            {
                Ray grow = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(grow, out hit, 1000))
                {
                    Debug.Log(hit.point);
                }
            }
      }

Now it's good and working as it should.

So, its time to end this little tutorial as it has already been very long. I hope you like it and if yes, please convey it through comments. Feel free to give an advice or ask something if you have any doubt. Thanks for reading.
Bye.  

Wednesday, January 14, 2015

How To Program a Matrix Calculator - (Java)

Hello Readers, Welcome to my blog; today i will explain you how to program a matrix calculator. I was recently working on a matrix calculator app for android so I thought to share my experience with you. 
This is just a basic idea of doing complex operations on a matrix like finding its determinant and inversing the matrix.
I've done it in Java (for Android) but the idea works for all languages and you can easily convert it into another.-

As you all know a matrix is a 2D array which means storing the value in form of a table. I also made a small overview of 2D arrays in last post -
newtonians3d.blogspot.in/2015/01/how-to-use-2d-two-dimensional-arrays-in.html
And also showed how to get its elements and a simple transpose operation Which was like this - 

float[][] matrix = new float[][] {  {1.2, 1.3, 2.0}, {1, 5, 2.1}, {1.5, 5.1, 2.6}  };
float[][] transposedmatrix = new float[3][3];
for(int i = 0; i < integers.length;  i++){
     for(int j = 0; j < integers[0].length; j++){
      transposedmatrix[i][j] = matrix[j][i];
     }
}

1. The Matrix Class - When dealing with many matrices, creating a class for matrix is always appreciable. It also enables us to take Full advantage of OOP (object- oriented programming). So this is how we define the matrix class -

public class matrix {
    private float[][] value;
    public matrix(float[][] cmatrix) {
    matrix = cmatrix;
    }


The method public matrix is the constructer of matrix class. If you don't know the constructer, it's a method which invokes when a object of that class is created and it returns that class. It can also takes arguments which is a 2D array in our class.
The constructer copies the given 2D array to its private variable value(float[][]) which will store the value of matrix's elements.
Now when you want to use this class you can write this -

matrix m1 = new matrix( new float[][]{ {4,5}, {7,6} });
OR
float[][] array = new float[][] ({ {4,5}, {7,6} }); 


2.Matrix Functions - Now so that we have declared our class we need to write functions or methods of this matrix class. Let's start with the easiest one - The Transpose Matrix operation.

 public float[][] transpose (){
        float[][] transposedmatrix = new float[value[0].length][value.length];
        for(int i = 0; i < value.length;  i++){
            for(int j = 0; j < value[0].length; j++){
                transposedmatrix[i][j] = value[j][i];
            }
        }
        return  transposedmatrix;
    }


This code is just fairly easy to understand it just make a new 2D array with rows equals to the columns of main matrix and columns equals to the rows of main matrix then just assign the [j][i] value to [i][j] of new 2D array.

3.The Determinant Function - 
While the determinant of matrix has the most applications in use its also very complex to calculate. The determinant of Matrix is calculated by following steps (in real life, not in programming)
 Step 1 : Suppose we want to calculate the determinant of the following matrix.
               4,  5,  6
               2,  3,  8
               1,  7,  9
         Now you can see there are 9 elements in this matrix.So there are 9 minors for all the 9 elements. To get the determinant. We have to calculate 
       the Minors of all the elements in a columns or all first elements of row.
Now what is the Minor?
It is the determinant of The matrix formed by cutting the current row and column and then finding the determinant of remaining matrix. 
It's difficult to read so let's illustrate it suppose we need to find the minor of first element in first row -
 Now let's cut the rows and columns adjacent to 4

The remaining portion forms a matrix and the determinant of this matrix is known as the minor of 1st element in first row.
now back to programming i Said we need to calculate the minors of either of all columns in first row or of all the 1st element in every row like in this example of 4,5,6 or 4,2,1.





If you still don't understand let's take the example to get remaining matrix of 2nd element in second row.-

The resultend matrix is [[4,6],[1,9]]
 
As the minors we need to calculate are many and all contain a 2D array its good to make class for minors. I don't find a suitable name for class so i named it remainingmatrix (pretty odd name) because it calculate the matrix of remaining elements.

public class remainingmatrix {
    public float[][] valuematrix;
    public remainingmatrix ( float[][] matrix ,int x,int y){

  }
}

This class also stores the result matrix in a 2D array as a property of class. And its constructer takes three arguments ie. one for the matrix itself and other to for the position for which remaining matrix is to be calculated. ex. if we want to calc. the remaining matrix for the above example we would write -

remainingmatrix m1r = new remainingmatrix(new float[][]{{4,5,6},{2,3,8},{1,7,9}} ,0,0)

To find the remaining matrix of first element of first row.
Now the rest of Code -

 public remainingmatrix ( float[][] matrix ,int x,int y){
        int order = matrix.length;

        int order2 = matrix[0].length;
        valuematrix = new float[order-1][order2-1];
        int incx,incy;
        for(int i =0;i<order-1;i++){
            for(int j =0;j<order2-1;j++){
                        if(i >= x){
                    incx = 1;}
                        else {incx =0;}
                    if(j >= y){
                        incy = 1;
                    }
                    else {incy = 0;}
                valuematrix[i][j] = matrix[i+incx][j+incy];
            }
        }
    }



I don't know how this idea came to my mind but it works well. Let me explain this code -
first it creates a new 2D array which is one shorter in length as the result matrix has one less rows and columns.
And then we declare two variable namely incx and incy and then made a nested loop for the newly created array.
Then it checks if the position of minor is less then the current loop position and if it is then inc variable is 0 other than its 1.
So, We completed this class let's move to our determinant which looks like this now - 

 public float determinant (float [][] value){
    int order = value.length;
    float result =0 ;


Notice that we included an argument for matrix that is it because we need to call this function inside this function. 
For that purpose we will use Recursion.
Now what is recursion?
Ans. Recursion is a situation in which one of the statement in a function make a call to the same function in which its present. It may sounds like Infinite loop but just as a loop has a conditional check to take program out of loop a recrusive also have a conditional check to take program out of loop.

We know that to find a determinant of matrix of order 2 is easy and single line code ie.-((value[1][1]*value[0][0]) - (value[0][1]*value[1][0])), so we will continously call the determinant function until the matrix becomes the order of 2 and then calculate the minors in increasing order first for 3, then 4... until the length of real matrix is reached.
Here is it --


  public float determinant (float [][] value){
    int order = value.length;
    float result =0 ;
        if(order==2){
        result =((value[1][1]*value[0][0]) - (value[0][1]*value[1][0]));
        return result;
        }

        else{
            float [] Minors = new float[order];
            for(float i :Minors){
           }
            remainingmatrix[] co_factors = new remainingmatrix[order];
            float inc =0;
            for(int i = 0; i < order -1; i++){
                co_factors[i] = new remainingmatrix(value , 0 ,i);
                Minors[i] = determinant(co_factors[i].valuematrix);
                if(i % 2 ==0){
                result += Minors[i] *value[0][i];
                }
                else {
                result += Minors[i] * value[0][i] * (-1);
                }
            }
            return result;
        }

    }


First it checks if the matrix is of length 2 and if it is return its determinant but if its not It creates an array of minors and remaining matrix(named co_factor) and then calculate its determinant.
After that it adds up the minors. If the position of Minor is odd its subtracted to result and if its even it's added to result. 
If you want to check the code functionality till now. I'am uploading the apk file of my android app that i made while developing it (The UI is not very good but main thing = it works)-
Although my code works for matrix of any length but i've made a limit to not exceed matrix of length 5 beacuse I'am not able to fit the UI in screen.(cause i'am not a UI developer, if someone can help me out with that please help) -
4Shared Link of Apk-


http://www.4shared.com/mobile/XmjpOoWAba/app-release.html

So that's the only first part of tutorial, i will post the second part when i have some time. Please +1 or comment please. I welcome you. Thanks for reading my post.
bye
- NEWTONIANS

Saturday, January 3, 2015

How to use 2D two dimensional arrays in Java (Complete Overview)

Recently I've been working on a matrix caalculator app for android, then I thought of posting something about 2D arrays in Java.
As you all know an array is collection of data of similar type. 
Let's first start with simple array.
This is how we declare an array. (of type integers)
int[] integers;  //an array of type int
This is only half declaration It will only complete when you specify its length or its element.

int[] integers = new int[5]    //an array of type int and length 5 or
int[] integers = new int[]{5, 54, 43, 48, 4};     //an integer array with elements  5, 54, 43,48 and 4

Or you can say its declaration is --
 type[] = new type[size];   or  type[] = new type[]{elements};

And When we want to retrieve its elements we use the array name with the index of element such as -

int 3rdelement = integers[2];

Now notice i wrote 3rd element but wrote the index 2. that's because the index of array's element start from 0. So the first element's index is 0, and for second is 1 and 2 for 3rd and so on.
If you want to get all elements of array at once you can use for loops like this -

for(int element : integers){
//This loop loops for every element in the array once

  
for(int i = 0; i < integers.length - 1; i++){
 this loop loops for every elements with i equals to the index of element


The simple array described above is one dimensional array because it stores elements in a line or in one row. 
The two - dimensional array stores element in rows and columns just like a table (or a matrix). The only difference between a Table(or a matrix) and a 2D array is that the numbers of columns in a row must be equal in a Table but it can be irregular in a 2D array. For example -


But That doesn't mean you can't use a 2D array to store a matrix. Its upto you.
We declare a 2D array by using two square brackets like this '[][]'. ie.-

int[][] integers;   //a two dimensional array of integers 

Now like the 1D array you need to specify either its size or element to declare it-

int[][] integers = new int[2][3]       //a 2D array with 2 rows with 3 columns each
int[][] integers = new int[][]{ {1, 4, 5}, {8, 9, 6} };      //a 2d array with elements specified



 The array defined can be written as-
 1  4  5
 8  9  6

Now to retrieve an element of 2D array we need to give its row index and column in square brackets- e.g.

int value = integers[0][2];

This will return the value of 3rd column of first row. Like the 1D array the index of first row or first column is 0. Therefore the first element in first column of first row can be accessed like this - integers[0][0].
Now there are two ways of retrieving all elements of a 2D matrix. First one is a for loop we used in 1D array -

for(int element : integers){
}

The other way of getting elements is by using a nested loop. Nested loop is made by starting a loop inside another loop like this. - 

for(int i = 0; i < integers.length;  i++){
     for(int j = 0; j < integers[0].length; j++){
       //You can get the current element by using value of i and j like this 'integers[i][j]
     }
}

Now one thing you will notice that i used integers.length in first loop and integers[0].length in second loop. The integers.length is the number of rows in a 2D array and integers[0].length return the number of columns in first row.
 That is the major difference in the above for loop and nested loop, ie. The nested loop only works for rectangular 2D arrays or we can say for 2D arrays in which the number of columns are equal in each row.

To solve this problem we can set the second loop to loop for all the elements in current row like this - 


for(int i = 0; i < integers.length;  i++){
    for(int j =0; j< integers[i].length; j++){
     }
}


Now that we know the basics of 2D array let's write an example Of 2D array-

This is just an simple example of transposing an array which means converting rows into column and columns into rows.

float[][] matrix = new float[][] {  {1.2, 1.3, 2.0}, {1, 5, 2.1}, {1.5, 5.1, 2.6}  };
float[][] transposedmatrix = new float[3][3];
for(int i = 0; i < integers.length;  i++){
     for(int j = 0; j < integers[0].length; j++){
      transposedmatrix[i][j] = matrix[j][i];
     }
}
So  this was something about 2D arrays in Java. Feel free to comment. Actually I'm not able to post so frequently being a school student and need to prepare for exams.

Tuesday, October 28, 2014

How To touch To orbit around player for Android in unity

Hi! readers I've recently converted the Mouse orbit Script that comes in standard assets to work with android and iOS touch devices. It's something very basic (easy to understand and modify) and very short. Just drag this script to the camera and assign a target around which you want the camera to rotate. Here it is...

//The standard mouse orbt script converted to work with touch devices (android and iOS) by Newtonians. Feel free to use or modify
//Check out the blog http://newtonians3d.blogspot.com/
using UnityEngine;
using System.Collections;

public class touchorbit : MonoBehaviour {
    private float x;
    private float y;
    public float xspeed;
    public float yspeed;
    private Touch touch;
    public float distance = 10;
    public Transform target;
    Rect margin;
    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        margin = new Rect(Screen.width * 0.5f, 0, Screen.width, Screen.height * 1.0f);
        float count = Input.touchCount;
        for (int i = 0; i < count; i++)
        {
            Touch tc = Input.GetTouch(i);
            if(margin.Contains(tc.position)){
            x += tc.deltaPosition.x * xspeed * 0.02f;
            y -= tc.deltaPosition.y * yspeed * 0.02f;
            }
        }
        Quaternion rotation = Quaternion.Euler (y, x, 0);
        Vector3 position = rotation * (new Vector3(0.0f, 0.0f, -distance)) + target.position;
       
        transform.rotation = rotation;
        transform.position = position;
    }
}


Another thing is that I've converted the original js script to c# so that it would be easier for a user to integrate the script into his projects.

This script is tested and works well but if you have some problem, please tell me.
Thanks.

Tuesday, September 16, 2014

Simple Third Person Character Movement Part II (Jumping, sprinting, falling and landing) : Unity 3D

Hello, Welcome readers to The second part of the tutorial of Third person character movement we started earlier. In this Part we will be working on sprinting, jumping and Landing System. 

 Watch in this video what we are creating and working on in the tutorial.





Since we are resuming our tutorial the first thing will be to download what we created earlier So, please download the file
 http://www.4shared.com/file/y6EyFbNmce/Tutorial_Start.html

It contains the complete finished part one of tutorial along with some new animations like jump, land, midair, and running. You may notice That quality of animation is very poor because i'am a scripter not an animator and this is the best I manage to get.
So let's start By creating a new Project and import this Unitypackage provided above. So, you can see some new animations and you can also hit play to see what we have already done in part one.


Now our first task is to make The player run when pressing sprint button (usually shift button). To make this work First open the animator window and drag the Run animation into the window and make a transition from walk to run with the condition speed > 1.5 like this.


Now create a Transition from run animation back to walk with condition speed < 1.5. To make all this work together we have to just write two lines in our code.
So, open our player script And In the void movement where we set the speed of animator like this -

anim.SetFloat ("speed",1);

Just replace this line with this -

if(Input.GetKey(KeyCode.LeftShift))
            {
            anim.SetFloat ("speed",2);
            }
            else {anim.SetFloat ("speed",1);
            }


So now our whole Function will look like this -

    void movement (float v, float h) {
        if (h != 0f || v != 0f) {
           
            //checking if the user pressed any keys
            rotate(v,h);
           
            //rotates the player in the intended direction
            if(Input.GetKey(KeyCode.LeftShift))
            {
            anim.SetFloat ("speed",2);
            }
            else {anim.SetFloat ("speed",1);}

            //then move the player in that direction
        }
        else {
            anim.SetFloat ("speed",0);
           
            //Stop the player if user is not pressing any key
        }  
    }


Now Hit the Play button to see your player sprinting when Left Shift is pressed. Although it not look like professional games That's because of the crappy animation provided by unity. But you can replace the run animation with our choice.

2. After The Sprinting part is Complete, We will focus on jumping and Landing. As much I know landing is more important part than jumping . The Logic of falling and landing is that we will create a variable grounded which will store if the player is landed or not. And whenever the grounded var become false we will change the animation state to falling and  when the grounded become true again we will change the state to landing and then back to idle.
So our first step is to create that variable. For this purpose we will raycast a ray down to compute the distance between player and ground. So add this to where we declare our variables (above all methods but inside the class brackets)

public float dist;
public bool grounded;
public Vector3 castpos;

You will notice I created a Vector3 castpos because I noticed that sometimes The main Transform of player goes under the surface where player is standing and it will give us wrong information. This is something like an offset to raycast position. And finally, add this in the Void Update


  castpos = transform.position;
  castpos.y += 0.2f;

RaycastHit hit;
        if (Physics.Raycast(castpos, -Vector3.up, out hit, 100.0F))
             dist= hit.distance;

if (dist < 0.5f) 
     {
       grounded = true;
    } 

    else 
    {
       grounded = false;
    }

You can now check the functionality by dropping from height and ensure that it works properly. now add this line also in function Update -

anim.SetBool ("land", grounded);

I know We never made any bool named land in animator before. Yes, we will make it now So, go back to the animator window and add a new parameter 'land' as a bool.


Now import the Midair animation (It's named Idle_JumpDownHigh_Idle) and the landing animation (it's named Idle_JumpDownLow_Idle) These are mainly jump up and down animation which i cropped for our purpose Into the animator window. And rename them correctly for better understanding.


I am trying to keep it simple but unfortunately we will have to make it some complex for proper functioning. What we will do now is to connect every state (idle, walk and run) to The midair state with condition land = false like this -


And now make a transition from from midair to land with condition land = true. And then finally a transition from land to idle with default condition Exit Time which mean when a state ended it's one loop. If you don't understand what i mean take a look at this -


Now if you play the game you can clearly see some mistakes and malfunctioning of our system such as the player leaves a platform it do not drop down to ground but get stuck at the corner that is because when the grounded become false it immidiately changes to midair without leaving the corner fully like this -


But don't get worried there is an easy solution to this problem, Click on of the Transition we made from idle, walk and run to midair And in the inspector you will see something like a timeline with two dots at the top of that timeline. (See the red circles to see the dots i was talking about)


The distance between these dots the amount of blending between two animations, As to solve our problem just widen the gap between then a bit according to my picture for all Transition. If you are not able to find the good point you can download the complete project (see below) which contains m setted animator controller with perfect parameters.

So now The Landing Part is completed we will do the jumping part. We will first start with the scripting. This is very very easy and simple just add this simple code in Void Update -

if (Input.GetKeyDown (KeyCode.Space)) {
                        anim.SetBool ("jump", true);
                } else {
                        anim.SetBool ("jump", false);
                }


Again i assigned the value of a parameter we do not created yet. So let's go back to animator window and create a bool parameter named 'jump' And drag the two jump animations provided by us. One of them is jumping in place and the other is jumping while walking or running ( Again the Quality of animations is poor cause i'am not a modeler or animator nor I have gaint mocap machines)


Now make a transition from Idle to jump (on spot) with condition jump = true and a return transition with condition Exit time 0. And hit play to check it's working condition which should be good.
Similarly do the same with jumping (while walking and running). Make transition from both walk and run with condition jump = true and a return transition with Exit time 0 But this time also add another condition Of speed according to situation like in return transition to walk speed  < 1.5 and In run speed > 1.5.


That's All for this tutorial, I hope you like it.You can also download the complete finished project via this link - 


Thanks for reading my blog.