Pages

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

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

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.

Sunday, June 29, 2014

A Simple and Efficient Touch And Drag RigidBodies For Unity 3D (Beginner Friendly) - Part 2

Welcome To Part 2 of Making a touch to drag script in unity. In this part we will add more realism to our project to make it more enjoyable.
1. After the completed first part you'll notice that when we released touch input the rigidbody do not fall realistic. It falls like its animated and not by physics. There is a very there is a very simple trick to do that. We will simply add a force to that object when the TouchPhase is ended (user released touch) equal to its delta position (The position delta since last change). To do that-
First declare a variable above all method and under class like we did in part 1 

private Vector2 deltaposition; 
privat float speed = 100;

We need to use a variable to store delta position because When the TouchPhase.Ended is called the delta position becomes zero and we can't use it in case Ended. The deltaposition is a very small value so we will multiply it by speed. Now add this under TouchPhase.Moved 

deltaposition = touch.deltaPosition;

It stores the Value of current touch delta position. And when the finger's released it do not get changed to zero, instead it remains the Last delta position untill touch's released. And add this line in TouchPhase.Ended

selection.rigidbody.AddForce(deltaposition.x*speed,deltaposition.y*speed,0);

Now you will notice the difference that how natural it looks now than before. But there is one problem left when you drag an object too fast the object will sprung into sky and never comes back ie we need to limit the deltaposition value not to exceed a specific value, for this we will use Mathf.Clamp so add this line under void update but remember to put it outside the for each loop - 
 
Mathf.Clamp (deltaposition.x, 0, 1);
Mathf.Clamp (deltaposition.y, 0, 1);


This will Limit the deltaposition value perfectly. If your not satisfied you can change the values of clamp according to your need.
Now this problem can be said solved.

Check Point - The script After All of above steps (check if have the same one)
Since, we are dragging any object on XY plane we do not add any force on z axis. But is want more functionality like moving in XZ plane you can easily do this by just simply rotating your plane 90 degrees so it faces the ground.
For now I have these improvement for our script, I will edit this post whenever i will come up with some new improvement to this project.

Thanks for reading my blog, bye;

Friday, June 27, 2014

A Simple and Efficient Touch And Drag RigidBodies For Unity 3D (Beginner Friendly) - Part 1

Hi! Looking for a simple and efficient Touch and Drag RigidBodies scripts for developing for Android, iOS or any other phones? Here is the tutorial for you.
First of all make a new project or you can also work in an existing project beacuse it will work for any RigidBody.

 

You will see a clear empty scene with just a Camera. We will attach our script with that camera. Here is how it looks without anything-




But for now click on create menu in hierarchy and then on plane to add a plane to your scene. This plane is very useful because we will later use it for Raycasting (with masking) to know current touch position. You will understand about it after some time. Now click on Layers and then Add layer. You will see 8 builtin layers which are not important for us add a user Layer 8 with any name, i used the name 'plane'. Make sure the plane's rotation is exactly with the camera and then parent the plane to the camera.
If you have not done something wrong your scene will look like this. (except the parenting step because i edited that later)


Now Add a Ground and some cubes or anything you want for Testing Our scripts, Just ensure that a rigidbody is attached to that cube or whatever you have choosen. disable the mesh renderer of the plane we created earlier for Raycasting. And Last add a point light to the scene to make it look 'fancy'. And
Here is our final scene setup.



Now comes the scripting Part, for that make create a new C# script and name it 'Drag' (as usual, without quotes) or whatever you like Then, open that up, And you will get something like this 

If you are a Basic user you should know that what void start and update does for your convinience.
Our First  Step is to declare the Variables we will use for our purpose (we will understand about them Later) - Add this above all of methods but under the class otherwise unity will bring an error.

 public Transform plane;
 private Transform selection = null;
 private Vector3 dist;


The plane is the plane we created earliear. Just assign this variable with the plane which we make the child of camera via inspector.
The selection transform will be assigned to the object which the user wanted to drag.i'll explain that later.
The Vector3 dist calculates the distance between the hit point and the transform of the selected object
Now add a foreach loop with array input.touches. If you don't understand, here is what i mean (add this under void update)

foreach(Touch touch in Input.touches)
        {


        }

This type of loop execute the code inside for any touches that exist in Input.Touches. If you still don't understand i refer you to unity Documentation.
Inside the foreach loop, Declare these variables - 

  Ray ray = Camera.main.ScreenPointToRay(touch.position);
 RaycastHit hit;


The first variable is a ray which goes in the direction pointed by touch input and the second is a RaycastHit which will give us info ablout the Raycast such as colliding object etc. The camera.main.ScreenPointToRay converts the user's 2d input into a 3d line going into the direction pointed by user's input position.

Now, Add a switch under the foreach loop for Touch Phases. code - 

 switch (touch.phase) {
            case TouchPhase.Began:

                break;
            case TouchPhase.Moved:

                break;
            case TouchPhase.Ended:

                break;
            }


This switch switches whether the user has began the Touch movement, or he is still touching or he has ended. Truly I don't know very much about switches but it is enough for all of us.

 Add this line to void Start of your script

plane.collider.enabled = false;
This will make the collider disabled by start. You can ignore its explanation because you will automatically understand it later.

CheckPost - If you have reached here successfully, your script will look like this -



using UnityEngine;
using System.Collections;

public class Drag : MonoBehaviour {

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
   void Update () {
        foreach(Touch touch in Input.touches)
        {
            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;
            switch (touch.phase)
            {
                case TouchPhase.Began:
               
                    break;
                case TouchPhase.Moved:
               
                    break;
                case TouchPhase.Ended:
               
                    break;
            }
        }
    }
}








If unity bring any error It means you done something wrong (Although it will give a warning about unused variables). Ok, So now the Setup is complete now w'll do some serious coding.
 Add these lines under case TouchPhase.Began: , TouchPhase.Moved:and TouchPhase.Ended: (actually replace the all code below with all the code in your script inside switch staement)


switch (touch.phase)
            {
                case TouchPhase.Began:


                if(Physics.Raycast(ray, out hit, 100))
                {

                 
                  if (hit.rigidbody !=null)
                    {
                      selection = hit.rigidbody.transform;
                      plane.transform.position = hit.point;
                    }
                }
                dist = new Vector3(hit.rigidbody.transform.position.x,hit.rigidbody.transform.position.y,hit.rigidbody.transform.position.z) -  hit.point ;
                plane.collider.enabled = true;
                    break;


                case TouchPhase.Moved:


                int layerMask = 1 << 8;
                if(Physics.Raycast(ray, out point, 100,layerMask))
                {

                   

                selection.rigidbody.constraints = RigidbodyConstraints.FreezePosition;
                selection.transform.position = point.point + dist;
                }
                    break;


                case TouchPhase.Ended:

                selection.rigidbody.constraints = RigidbodyConstraints.None;
                selection = null;
                plane.collider.enabled = false;
                    break;
            }


At First Sight, this looks like a mess of code but you will understand it. that's the reason i make the title Beginner friendly
I'll explain it step-by-step 

Under TouchPhase.Began 
We fire A raycast from the ray we created earliear which originates and move towards the direction of touch input.Then, If it hits on a rigidbody assign the selection variable to the transform of that rigidbody, and set the position of the plane for raycasting to the point where the raycast hit. Then we calculated the distance between the hit point and colliding rigidbody's transform. This offset(var dist) is very essential because if we will not use it The object center will always be at your finger's position even if you pulled it from the corner of object which will give jerky motion to object.
And at last plane collider is being enabled to detect touch position in Moved phase.

Under TouchPhase.Moved
Declaring a int for ignoring the raycast for all object except the plane (which we defined earlier in scene setup). Then raycast the current touch position which hit the plane and then assign the position of that point to the rigidbody the raycast hit(in Touchphase.began). Then we freezed the movement of Rigidbody To make it move according to the touch movement without falling with gravity.(actually this make dragging rigidbody very enjoyable as the rigidbody will only rotate in air but not fall).

Under TouchPhase.Ended
when user stopped touching the screen. We just rollback the changes we did like we disabled the freeze position constraint. And empty the selection variable. And also disabled the plane collider so that it will not come in the way when the user will again try to drag another rigidbody. (that's why we disable the collider in void start, I hope you guessed that earlier).

And hit the play button if you are using realtime debugging or build and play in your device (if you have one) or in a emulator and you will see the cube or the test rigidbody you choosed acording to your finger. At this point although it look very good but not totally realistic. We will add more realiatic effects to this in part 2. 
That is all for part 1. In Part 2 we will add some more physical effects to make it more real and enjoyable.

Here is The unitypackage of this project if you just want some instant Action or you feel comfortable to understand it better with source code. So here is the link from 4 shared - 

http://www.4shared.com/file/2DBk80hgce/Touch_n_Drag_part-1_source.html

Let me know if you have problems with download. I'll make the part as soon as i can. Thanks for reading the post. I'll hope you like it. bye 

[EDIT] The part 2 is complete you can check it out at this link - 
www.newtonians3d.blogspot.com/2014/06/a-simple-and-efficient-touch-and-drag_29.html