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


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;

No comments:

Post a Comment