Search code examples
unity-game-enginetouchtransform

Unity2D move transform on touch


I want to move my main player as the user moves its mouse (on PC ) or finger (on mobile devices) enter image description here

I made a simple illustration. If I move my finger 10 units in left, i want the player to move 10 units to the left as well. How can I achive this, for both mobile and PC ?


Solution

  • Vector3 screenPoint;
    Vector3 offset;
    
    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }
    
    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }
    

    Add this code to your player's script.

    Edit: This code is so simple to convert it to "move via click from every where". The only problem was OnMouse* functions works only when you click the scripted and collidered object. Just change it with Input.GetMouseButton and its solved.

    bool flag = false;
    
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (!flag)
            {
                flag = true;
                screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
                offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
            }
    
            Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
            transform.position = curPosition;
        }
        else
        {
            flag = false;
        }
    }