Dragging an object by touch?

This piece of code doesn’t move my cube to the position of my finger. There’s no proper touch input tutorial on internet as well so I’m stuck. I don’t know much about touch inputs. Any kind of help is appreciated.

using UnityEngine;
using System.Collections;

public class CustomTouch : MonoBehaviour {

GameObject cube;
private Ray ray;
private RaycastHit rayHitInfo = new RaycastHit();
private Touch currentTouch;

void Update () 
{
	if ( Input.touchCount > 0 )
	{
		for (int i = 0; i<Input.touchCount; i++)
		{
			currentTouch = Input.GetTouch(i);

			if (Input.GetTouch(i).phase == TouchPhase.Moved)
			{
				ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);

				if ( Physics.Raycast(ray, out rayHitInfo))
				{
					Vector2 v2 = currentTouch.deltaPosition;
					Vector3 v3 = new Vector3(v2.x,v2.y,transform.position.z);
					cube.transform.position = v3;
				}
			}
		}
	}
}

}

What I would do is start from some working mouse drag code and then modify it for touch. There are a number of drag and drop scripts posted to UA. Here is one I recently posted:

http://answers.unity3d.com/questions/595903/gameobject-dropping-and-laging-while-dragging-on-a.html

This script only works if the camera is axes aligned. We use the third-party FingerGestures package for our touch input, so I don’t have a lot of depth with the native touch interface, but here is untested conversion to C# and touch of the script.

using UnityEngine;
using System.Collections;

public class Drag2 : MonoBehaviour {
	private float dist;
	private bool dragging = false;
	private Vector3 offset;
	private Transform toDrag;

	void Update() {
		Vector3 v3;

		if (Input.touchCount != 1) {
			dragging = false; 
			return;
		}

		Touch touch = Input.touches[0];
		Vector3 pos = touch.position;

		if(touch.phase == TouchPhase.Began) {
			RaycastHit hit;
			Ray ray = Camera.main.ScreenPointToRay(pos); 
			if(Physics.Raycast(ray, out hit) && (hit.collider.tag == "Draggable"))
			{
				Debug.Log ("Here");
				toDrag = hit.transform;
				dist = hit.transform.position.z - Camera.main.transform.position.z;
				v3 = new Vector3(pos.x, pos.y, dist);
				v3 = Camera.main.ScreenToWorldPoint(v3);
				offset = toDrag.position - v3;
				dragging = true;
			}
		}
		if (dragging && touch.phase == TouchPhase.Moved) {
			v3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
			v3 = Camera.main.ScreenToWorldPoint(v3);
			toDrag.position = v3 + offset;
		}
		if (dragging && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)) {
			dragging = false;
		}
	}
}

Note this script will only drag an object if it has the tag ‘Draggable’. You can remove this check (it is in the Raycast() line).

I didn’t read it fully, but I think you shouln’t youse deltaPosition (that’s for the position change, such as swiping), instead try Input.GetTouch(i).position.y and Input.GetTouch(i).position.x

edit: I’m also kinda new to developing for touch devices (Android for me), I followed some of this guy’s tutorials and actually helped me a lot: Devin Curry - YouTube

[untested and from memory] Using one touch is pretty much the same as using one mouse. But, the one difference is that iPad touch positions (and probably all touches) are reported in viewport coords (can print them in a guiText to be sure.) That means they are always from 0-1. Mouse positions are in pixels (screen coords.)

So, the code above should be using ViewportPointToRay (or multiplying touch.position by Screen.width/height, but that’s a pain.) If I’m correct, as it is now, screenPointToRay is always seeing tiny 0-1 numbers, treats them as pixel (0,0) and thinks you are always touching the upper-left(?) corner of the screen.

There is a script which comes with Standard Assets of Unity called “DragRigidbody.сs”

Just add this component :slight_smile:

Also you will be needed to change some constants inside of script to get better results as you expect.

Hi @Nick4 Here’s my script. It works likely OnMouseDown(), OnMouseDrag(), and OnMouseUp() of course with multi touch support (The RayCast here is 3D):

    public GameObject[] touchedObj = new GameObject[5];

void Update ()	{
Touch[] myTouches = Input.touches;

	//Get how much finger/tap in screen
	for (int i = 0; i < Input.touchCount; i++) {
		Vector3 mainPos = Camera.main.ScreenToWorldPoint (myTouches *.position);*

_ Ray ray = Camera.main.ScreenPointToRay (myTouches .position);_
* RaycastHit hit;*
* mainPos.z = -4f;*
* if (Physics.Raycast (ray, out hit, 20f)) {*
* //OnMouseDown()*
_ if (hit.collider != null && myTouches .phase == TouchPhase.Began) {
touchedObj = hit.transform.gameObject;
* print (“Obj Touched!!”);
}
}
//OnMouseDrag*

int ID = myTouches*.fingerId;
if (touchedObj [ID] != null){
touchedObj [ID].transform.position = mainPos;
print (“Obj Dragged!!”);
}
//OnMouseUp()
if (myTouches.phase == TouchPhase.Ended && touchedObj[ID] != null){
touchedObj [ID].GetComponent ().AddForce (Vector3.right * 50f);
touchedObj [ID] = null;
print (“Obj Released!!”);
}
}
}*_

@robertbu

Hello … I have some objects moving in a grid. I would be glad if you could help me how I need to write code to move these objects only left, right and forward on the phone.

Drag 2D game object by touch - 100% working

click this link: Drag and Drop for Mobile & Desktop in Unity - YouTube
If you’re installed input system in unity registry. it will not work, remove and use.

credit for the developer