- Home /
Touch - drag different objects
Hi, I'm trying to make draggable objects on the Stage for Android and iOS, looking in the forum I found this script but it doesn't work, have any suggestions?
The most problematic thing is to isolated the touch event on a specific game object.
This script is attacched to every draggable object on the stage:
#if UNITY_ANDROID
void Update () {
foreach (Touch touch in Input.touches){
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, 100f)) {
//Debug.Log (hit.collider.transform.position);
if(touch.phase == TouchPhase.Began){
var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, cameraTransform.z - 0.5f));
//objectSelected();
}
if(touch.phase == TouchPhase.Moved){
if (hit.collider.gameObject == this.gameObject) {
var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, cameraTransform.z - 0.5f));
//objectDragged();
}
}
if(touch.phase == TouchPhase.Ended){
//objectDeselected();
}
}
}
}
#endif
Answer by LostInCode404 · Jun 29, 2014 at 09:28 AM
You are going in the right direction but need some changes. Checkout the tutorial i have made for touch and drag objects. Here is the link - www.newtonians3d.blogspot.com/2014/06/a-simple-and-efficient-touch-and-drag.html I hope this tutorial may help you.
Your answer
Follow this Question
Related Questions
2D Raycast touch 1 Answer
Make sphere shoot to Touch.position error 1 Answer
Drag Object, same speed as mouse/touch 3 Answers
Timer Freeze Problem 1 Answer
Drag and Swap two object using touch 0 Answers