How to drag gameObject by dragging any part of the screen?

Hello everyone,

So far, I am able to drag my object along the x-axis; however, my current code requires me to click on the gameObject itself to move it. I need to be able to click anywhere on the screen and move the gameObject in the way that I currently have it. Currently, if I click on the screen and move my mouse, nothing happens.

Here is my current code that I attached to the affected gameObject:

void OnMouseDrag()
    {
        Vector2 curPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector2(curPosition.x, transform.position.y);
    }

OnMouseDrag work when you click on collider or gui element, so when you click on free space nothing happens. I think you need to use Input.GetMouseButton(0):

void Update()
{
   if(Input.GetMouseButton(0)) // 0 for left and 1 for right click
   {
      Vector2 curPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition)
      transform.position = new Vector2(curPosition.x, transform.position.y);
   }
}
1 Like

Thank you, this solved my problem! Now I need figure out how to convert this to touch screen for iOS.

Simple: replace Input.GetMouseButton(0) to Input.touchCount > 0 and Input.mousePosition to Input.GetTouch(0).position.

Perfect, thank you. I was researching, and I came upon a few threads in the forums that said you actually don’t have to convert this if you don’t want to; Unity will convert this for you depending on where the game is run. Have you ever heard of this?

Something I heard, but Input functions are not the one what should change. In mobile game must be other graphic, mesh, etc so this is the smallest problem.

Right, I will need to adjust the the resolutions depending on screen sizes.