1

I'm new to Unity and I'm a bit surprised that there is no optional auto-conversion of basic touch actions to mouse. Well, at least none that I've found after 2 hours searching.. Anyways.. I have the following script to drag a 2D sprite:

void OnMouseDrag()
{
    if (dragEnabled) { 
        Vector3 point = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, (transform.position.z - Camera.main.transform.position.z)));
        point.z = transform.position.z;
        transform.position = point;
    }
}

Pretty straighforward.. But now I need to make this work for touch, but every solution I found are either from 2011, fail to work and/or are dozens of lines long..

Is there a simple way to "convert" this to mobile, or, even better, make one solution that works for both cases?

sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • 1
    See my question in here : http://stackoverflow.com/a/41392130/6786634 I think this is already have an answer. – Dennis Liu Mar 16 '17 at 02:37
  • This is for UI right? I'm looking to drag non-UI sprites – sigmaxf Mar 16 '17 at 02:39
  • 1
    The new UI API is meant to work on both mobile and desktop. See the the post comment it described in there and the answer have NON UI OBJECT too. – Dennis Liu Mar 16 '17 at 02:40

1 Answers1

2

As @DennisLiu said: if you look to the end of @Programmer's answer, you'll find the way to do it with 3D objects (or simply non-UI objects). The easiest way to achieve what you're looking for is using the EventSystem component with a PhysicRaycaster (same as the default GraphicRaycaster used for UI raycasting but for 3D objects):

  • Add a PhysicRaycaster to your MainCamera object (this ones requires a Camera)
  • Add an EventSystem on the object you want
  • Add an InputModule (can be Standalone or Touch one in your case) on the same object as the EventSystem component

Then you simply have to subscribe to events as @Programmer explained.
You can fin the list of the supported events here.

Community
  • 1
  • 1
Kardux
  • 2,117
  • 1
  • 18
  • 20