- Home /
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;
}
}
}
}
}
}
Answer by robertbu · Dec 20, 2013 at 07:06 PM
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).
[2]: http://answers.unity3d.com/questions/566327/drag-object-relative-to-camera.html
Great. This works better than anything I came up with / found on internet. I will also check out finger gestures package. Thanks for bringing it up as well.
I know that that I can zombiefied this thread, but can you help me on how to convert this script so that if I drag the gameobject it only moves on the x-axis?
Answer by MadJohny · Dec 20, 2013 at 06:28 PM
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: http://www.youtube.com/channel/UC0Ahv9Y12r2To-syiUoR8Lg
Yeah. I tried that before. It just places my object somewhere out of the screen. I also used this cube.transform.position = Camera.main.ScreenToWorldPoint(v3) It seemed like it didn't have effect at all. I think problem is that "currentTouch.position" is not as accurate as it's supposed to be but I'm not sure.
Answer by Owen-Reynolds · Dec 20, 2013 at 06:56 PM
[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.
Answer by U_Ku_Shu · Aug 05, 2016 at 09:51 PM
There is a script which comes with Standard Assets of Unity called "DragRigidbody.сs"
Just add this component :)
Also you will be needed to change some constants inside of script to get better results as you expect.
Answer by Keyserjaya99 · Dec 16, 2016 at 08:45 AM
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 [i].position);
Ray ray = Camera.main.ScreenPointToRay (myTouches [i].position);
RaycastHit hit;
mainPos.z = -4f;
if (Physics.Raycast (ray, out hit, 20f)) {
//OnMouseDown()
if (hit.collider != null && myTouches [i].phase == TouchPhase.Began) {
touchedObj [i] = hit.transform.gameObject;
print ("Obj Touched!!");
}
}
//OnMouseDrag
int ID = myTouches[i].fingerId;
if (touchedObj [ID] != null){
touchedObj [ID].transform.position = mainPos;
print ("Obj Dragged!!");
}
//OnMouseUp()
if (myTouches[i].phase == TouchPhase.Ended && touchedObj[ID] != null){
touchedObj [ID].GetComponent<Rigidbody> ().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.
Your answer
Follow this Question
Related Questions
Ragdoll 2D character controller help 0 Answers
Touch and Drag for Android problem 0 Answers
How to change the scaling of a gameobject during runtime? 2 Answers
I'm not sure how to approach this. 2 Answers
How to force Eventsystem Drag 1 Answer