Unity touch controls, accurate finger following

Hi, I’m recently new to Unity and touch controls, I have been following the Unity scripting API’s and found this piece of code:

// Moves the object according to finger movement on the screen

var speed : float = 0.1f;

function Update()
{
	if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
	{
		
		//Get movement of the finger since the last frame
		var touchDeltaPosition : Vector2 = Input.GetTouch(0).deltaPosition;
		
		// Move object across the X and Y plane
		transform.Translate (-touchDeltaPosition.x * speed, touchDeltaPosition.y * speed, 0);
	}
}

This manages what I want to achieve, the problem is, the object doesn’t accurately follow my finger, sometimes it will be too fast or sometimes it will be too slow, I would like it to stay underneath my finger at all times without straying off. The speed variable doesn’t seem to make much of a difference.

Here is a video to the problem I’m having, hopefully give people and idea of what’s wrong:

Is there a way I can accomplish this?

The problem is that this code moves the object based on the movement of the finger, but it doesn’t make the object follow the finger.

If you want the object to follow the finger you need to:

  1. Get the coordinates of the finger in world space (instead of screen, which is what the touch gives you). You can use ScreenToWorldPoint (or similar) and touch.position.
  2. Make the object translate to that position over time (Using something like SmoothDamp)

Try that and let us know.

#pragma strict

private var pos : Vector3;

function Start () {

}

function Update()
{
	
	pos = Camera.main.ScreenToWorldPoint (Vector3 (Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 5));
	
	transform.position = new Vector3(pos.x, pos.y, pos.z);
}

Thanks Andres Fernandez, I was playing around for a while and managed to get it working with Camera.main.ScreenToPointWorld and Input.GetTouch(0)

As of now, I have it following my finger on the x and y axis with a fixed z position, should I improve upon this, I will update my answer.