- Home /
Question by
shenhuang · Oct 27, 2016 at 07:01 AM ·
mobiletouch controls
How to implement touch to drag for multiple game objects?
Hi I was trying to drag 2 objects, and my attempts are failing, here is my code. I do not truly understand how Unity touch works, is there anyway I would know?
Here is the function inside update:
private void dragToMove () {
if (Input.touchCount > 0) {
int touchIndex = 0;
bool touched = false;
Touch touch;
Collider2D collider2D;
Vector3 touchWorldPoint;
do {
touch = Input.GetTouch (touchIndex);
touchWorldPoint = Camera.main.ScreenToWorldPoint (touch.position);
collider2D = GetComponent<CircleCollider2D> ();
if (collider2D.OverlapPoint (touchWorldPoint) && touch.phase == TouchPhase.Began) {
isDragged = true;
}
touchIndex++;
} while (touchIndex < 2 && !isDragged);
if (isDragged == true) {
shootProjectile ();
switch (touch.phase) {
case TouchPhase.Moved:
float cameraHeight = Camera.main.transform.position.z;
if (touchWorldPoint.y < -2) {
transform.position = touchWorldPoint - new Vector3 (0, 0, cameraHeight);
} else {
transform.position = touchWorldPoint - new Vector3 (0, touchWorldPoint.y + 2, cameraHeight);
}
break;
case TouchPhase.Canceled:
isDragged = false;
break;
case TouchPhase.Ended:
isDragged = false;
break;
}
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612095518im_/https://answers.unity.com/themes/thub/images/avi.jpg)