Pages

Showing posts with label Newtonians. Show all posts
Showing posts with label Newtonians. 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.

Saturday, September 6, 2014

Simple Third Person Character Movement in Unity 3d (with Mecanim) - I

Hi, welcome back readers. Many a people want to make a third person game in unity. Here is simple third person movement tutorial with my project folder too. In next tutorials, we'll add jumping, sprinting and some other basic moves.Have a look at this video of the completed tutorial in action.





This is what we will make after the tutorial.

Be patient because it may seem to be a long tutorial but it is as informative as long it is. Also it is so user friendly and easy to understand that a person not knowing anything about Unity may also give it a try.

To make a third person game you will need a 3d character model and some basic animations like walk, idle etc. You can use your own models but if you don't have it I will provide you the sample assets which are used in this tutorial here -

http://www.4shared.com/file/0R8OkHHhce/Free_Assets.html

The model used is the free soldier model made by Mixamo and the animations are provided by unity in their raw mocap data unitypackage. And that crappy environment is made by me it's not much good cause i'm not a 3d modeller.

1. So first of all we will open unity and make a new project. So go to File --> create new project to make a new project and under 'import the following packages' select scripts.unitypackage as need the camera orbit script contained in it And name the project of your choice. you will see something like this.-


Now we will import the Free assets package (link are provided above) by going Assets --> import package --> custom package and then import the file which you downloaded. Select all items and click import.
Now you will see a soldier model, idle and walk animations and the crappy environment i was talking about. (notice that it looks like a simple box in project view but it's actually a interior model)

2. So now we will prepare our scene for our use. So drag the 'dfdf' model (the crappy environment) into the scene area and you will see the model int the scene view (now you will see the interior part)


As the environment looks very dull now we will add a light to illuminate it. So add a point light and place it in the center of room just below the ceiling to get a decent lighting


You can play with the range, colour and intensity of lights to get the lighting as you want. Now drag the soldier also and place it at any place in the interior. Now save your scene.

3. As our scene preperation is done now we will make the animating part done. Go to the animation folder in project view and you will see an idle and walk animation. The mecanim system uses animator controller for the logical creation of animation states So, create a new animator controller by right click --> create --> Animator controller and name it and double click it to open the animator window like this -


If you don't know the very basics of animator controller please take a look at unity Docs they have  lot of information about it. Basically, in mecanim you create states (animation clips) for different animation like walking, standing, running and then you connect them with transition with some conditions. And if that condition is met the transition will occour from one state to another othewise it will loop in the present state.

So click on the tiny arrow in the idle animation icon and it will show you the content and you will see a 'playing' icon with name 'idleR...' (it's actually the animation part of the Fbx file) and Drag it into the animator window and it will create a new state with it. like this -



Now also drag the walk animation in animator. You will notice that the idle animation is of yellow colour because it's the default state that will be played after starting game. You can change the default state by right clicking on state --> 'Set as default'. Now click the + icon just ahead the parameters to add a new parameter and set its type as float and then name it speed. Now we will create transitions from idle to walk.
For that right click idle state and click on make transition and then click on the walk state like this.


Now click on transition and you will see its properties in inspector. There you will see a property called condition. when the conditions specifies under this field met, the transition will  occour. By default a transition occours when the animation completes one loop ie. exit time. But we need it to be changed by speed parameter so change the exit time to speed. Now there is a field for a greater than or less than value which specify the condition for the transition, We need the walk animation at value of speed 1 and the idle at 0 so change its value to greater than 0.5.
Similarly make a transition from walk to idle, now with parameter speed less than 0.5

Now go back to the scene and select player gameobject, In the inspector under the Animator there will be a property called controller So, drag the animator controller we just made into that field and our animation part is done.

4.LOGIC Behind our third person shooter. Like in most of the third person games present today like max payne, gta 4. The player rotation system is relative to camera and user inputs eg. when user press right arrow, first the player rotates in the exactly right direction as viewed by user (or you can say camera) in other words the player rotates in the direction of camera + 90 degrees and start walking in that direction  similarly if he presses down arrow the new rotation will be camera +180 degrees and if player presses both right and up arrow the direction will be camera + 45 degrees. Here is a diagram of all possible values of The new Rotations.

 

5. Now we will do the scripting part so make a new C# script and name it playerscript or whatever you like And then open the script in editor.


It will show some template for you to start with. We will first declare some variables which are essential for our need. So write this above all methods but inside the class just below the line that declare your class playerscript : Monobehavior like this -

public class playerscript : MonoBehaviour{
Animator anim;
public Quaternion newrotation;
public float smooth = 0.05f;
public Transform camera;

anim is the animator that will take care of assigning the speed parameter we created in animator window through user inputs. Next we declare a quaternion, As this tutorial is for beginners i will not talk much about them because they are not easy to understand i also not use them very much because of that. As in general we all know that quaternions store rotations and the newrotation variable will store the current rotation the input keys shows. Later we will slerp the player rotation from its rotation to this newrotation which I was telling about when explaining the logic of third person shooter.
The third variable smooth specify how smoothly player rotates in the intended direction. And the last variable specify the Transform of camera, As you know all the rotations will be relative to this cameras rotation, so this is also very important for us.

Now under the void start write this -

anim = GetComponent<Animator>(); 

This will access the animator from the player through scripting.
Then we will take the user input through Axis So, write this under void Fixed Update

 float v = Input.GetAxis ("Vertical");
 float h = Input.GetAxis ("Horizontal");
 movement(v,h);

These will store user horizontal and vertical inputs in variables To be used  later. And the next line will get error at this  time because we havn't made any fucntion. Next we will create that function we called earlier that will move our player according to inputs. The basic syntax for a function in C#  is return type function-name(arguments){main body} so above all methods but inside the class create a new function for movement which take Input Axis as arguments like this -

  void movement (float v, float h) {
        }


Now under this function write this -

    if (h != 0f || v != 0f) {
    //checking if the user pressed any keys
            rotate(v,h);

    //rotates the player in the intended direction
            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
        }


Here we again called another function rotate we do not created which we will do next. First of all it checks if their is an input from user and then sets the speed of animator to 1 (remember we aplied the condition from idle to walk with greater than 0.5, thus the condition is met and player will start moving).
Now comes the main thing of rotating the player in relative to camera. We have already invoked the rotate function so now we will create that function.

  void rotate(float v,float h) {
     }

Add this whole code under this function

    if (v > 0)
        {
            if (h > 0)
            {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+45,0);
            }
            else if (h < 0)
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y+305,0);
            }
            else
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y,0);
            }
        }
        else if (v < 0)
        {
            if (h > 0)
            {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+135,0);
            }
            else if (h < 0)
            {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+225,0);
            }
            else {
                newrotation = Quaternion.Euler(0,camera.eulerAngles.y+180,0);
            }
        }
        else
        {
            if (h > 0)
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y+90,0);
            }
            else if (h < 0)
            {
            newrotation = Quaternion.Euler(0,camera.eulerAngles.y+270,0);
            }
            else {
                newrotation = transform.rotation;
            }
        }

     

Don't think this code is too big this code is also as easy understand as big it is. In short what it does sets the new rotation's value according to user's input and relative to camera. Remember the diagram -


Now so that the new rotation's value is specified we will slerp it into player rotation so add this code below code above;

newrotation.x = 0;
newrotation.z = 0;
//We only want player to rotate in y axis
 transform.rotation = Quaternion.Slerp (transform.rotation,newrotation, smooth);

//Slerp from player's current rotation to the new intended rotaion smoothly 

Now, with that our scripting part is done and our tutorial is almost finished.

 6. Go back to the Unity Editor and assign this script on the the player. And in the inspector assign the camera Transform field with the main camera. Now assign the Mouse orbit script to our main camera and assign the target to our player and set the distance to 1.3. 

Then hit play and you will observe a realistic third person character movement. Your character is moving as it should but there is one problem that rotates around the legs of character because pivot point of character is at legs.
To solve that problem just click on gameObject --> create empty and a new game object is created, now rename it as target and place it just at the chest of our soldier (Place it in character carefully and check it from all views so that it is at correct position.) now make this object a child of player by simply dragging the object onto the player's gameobject in hierarchy. Now in the target field of Orbit script of main camera drag this newly created target object and then hit play and enjoy your created Third person game.

To add the physics to the player and increase the realism simplay add a capsule collider and rigidbody to player see it in action You can also bake the environment with unity's lightmapper to add more realism. 

Here is the link to our project folder 

http://www.4shared.com/rar/ziw5DVrSce/Simple_TPS_Character_movement.html 
 
Thank you for reading my this very long tutorial, feel free to give any suggestions or complaints. Keep checking for further updates to this tutorial in which we would be trying to add jumping, sprinting and some cool basic moves. One more time thank you and have a good day.

Sunday, August 10, 2014

Rayfire Wall Breaking Tutorial For beginers in 3ds Max

Hello, welcome to my blog i presenting you a little tutorial for breaking walls in rayfire. This tutorial is for beginers who wants to make some cool demoltion effects in 3ds max. That's why it is divided in steps. So there we go -

1. First of all open 3ds max and you will get a blank viewport like this - 




2. Then go the primitives and create a ground plane and a wall which is a box of your desired size. Be carefull when selecting the size for wall do not make it thick as it will not create good result. Here is what i have. -



3. Then we will make an object which will act like a bullet to break the wall. You can choose anything but i choosed a sphere for that purpose. So, make a sphere of deired radius and place it in the front of wall.


4. The next is to animmate the sphere object so it appers to go through the wall destroying it. for that first click on autokey button on the bottom right corner just below the timeline. And you will see your viewport's border become red. Then go to the first frame and place your ball right in front of wall like this -


Then move the time slider to frame 15 and move your sphere to the opposite side of wall right through the wall like this -



 Now turn off auto key and the animating part is done.

5. Now since we have animated the sphere we will have to fragment the wall into fragments. For that you can use the fragments tab in rayfire window but that is used for instant fragmentation and is not very good for our purpose. I will use the rayfire fragmenter modifier because it is much better than the fragments tab in rayfire window and gives you a better control over the fragmentation process. So select your wall go to the modify tab and add the rayfire fragmenter modifier to the wall.


 Now you will see the parameters of the fragmenter modifier. Most of the parameters are godd by default we don't need to change those, but just few. So change the count from 20 (default value) to 100 to get more nice result. And then click on fragment button and you will see your walls divided into fragments like this -



 NOTE - I've choosen the count property of 100 so it can run in low specs CPu's also. But if you have a mid end or high end PC i reccomend you atleast 250 for a good result as 100 is very low and does not look very realistic if you are demolishing a wall in a big project or making a vfx film.

If you are not able to see fragments press F4 to toggle 'Edged faces' and you will see the fragments clearly. Now if you are not happy with fragments you change the seed to get your desred result and you can also increase the count to get more good looking result but it will also increase the time of simulation depending on your CPU. At last if your are satisfied with fragments click on detach button to detach each fragment as an separate object. And the Fragmentation Process is finished.

6. Now, since the animation and fragmentation part is done we will use the rayfire to make the demolishion effects.
 So open the rayfire floater from create tab --> geometry tab --> 'rayfire' menu --> 'rayfire' button --> 'open rayfire floater' button and a new rayfire window will appear. You will see two lists one for dynamic bodies and one for static and kinematic bodies. carefully Select all the fragments of the wall and then click on add button under the 'dynamic/impacts' objects list. Also select the sphere and add it in the dynamic objects list. Finally add the plane in the static and kinematics object list.

7. In this step we will change some parameters of simualtion and simulate the breaking of wall. So, Go to the physics tab in rayfire floater and you will see a property called start frame this is very important for us. In this field you will have to specify the frame in which the simulation should be started.
 Specify that frame in which the sphere is just about to hit the wall. Make sure that it has not hit the wall yet like this (my frame is 8 but yours can be different depending on how much you moved your sphere in step 4) - 


It is neccessary to set this frame carefully or it will lead to undesireable effects. There is also a property called Time scale you can change that to create slow-motion effects. 
Now as we have all things set up let's destroy the wall by clicking simulate and see the wall breaking realistic. 


You may notice that sphere initially had more speed but after colliding it reduces and it follows the realistic path (parabolic, to be natural), even though we animated it, and you know what, That's the power of RAYFIRE. Rayfire detects the speed of object even when its animated and then interpolates it in physics simulation. 

Note - To make the simulation more accurate and realistic you can increase the count  property in rayfire fragmenter.

8. We can now assign materials to the objects, to make it look fancy and a little bit wow!!




That's All for this tutorial have a good day. I hope you like it and feel free to suggest, complain or thanks via comments. If someone has any problem in following this tutorial please ask me the problem and i will help you. bye.









Saturday, July 12, 2014

Tips #1 Rotating player with camera in TPS

I will show how we can rotate player with the camera, just like in max payne 2.

what we have to do is create and apply a script on player.
In function update, write

transform.eulerAngles.y=Camera.main.transform.eulerAngles.y

transform.eulerAngles.y will give the state of rotation of main camera about vertical axis whose value we are assigning to the state of rotation of the player. We can use other cameras as well, for that instead of camera.main.transform, we have to give another variable of type transform whose rotation we want the player to follow. Keep reading for more tips.

Wednesday, July 2, 2014

One Way Platform : Unity Tutorial

Hi friends! Here is the tutorial for making One Way platforms in unity. I've got a very simple technique to do this job so that no one gets stuck at this problem.

Here is what you have to do.

Make a platform and add a box collider to it.

Create a Gameobject (it is used for collision checking), as a child to the platform,name it as colcheck, and add a box collider to it just below the box collider of the platform. Make sure that "is trigger" checkbox is on so that we can check if the character or any kind of player is in contact with it or not. It should look something like this.






Go to tags and layer an create a new tag 'platform' and assign this to all the colcheck game objects.
Now we will write a script and add it to the colcheck game object we just created. Here it goes.

function Start () {

var colliderofplatform : BoxCollider2D;

//It is collider of main platform, assign it in inspector
 
var oneway : boolean;

//this variable will be made true when the players is just below the platform so that the Box collider of collision checking game object can be disabled that will allow the player to pass through the platform

}

function Update () {

if (oneway)
  colliderofplatform.enabled=false;


 if (!oneway)
  colliderofplatform.enabled=true; 


//Enabling or Disabling the platform's Box collider to allowing player to pass  
}



function OnTriggerStay2D(coll : Collider2D) {

if (coll.gameObject.tag == "platform")
   oneway = true;

 //Checking the collison of the collision checking gameobject we created for checking if the player is just below the platform and needs to ignore the collison with the platform}
 
}

function OnTriggerExit2D(coll: Collider2D) {
   oneway = false;


//It is done so that we can reactivate the collider of the platform for the player to stand on that platform
}


Now you will see that our one way collider is working the way it should. If there is some problem with it, add it to comments and I will fix it.

I'll upload the project file also. Keep reading, keep enjoying and playing with Unity, thats a nice engine. 

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