4

I'm trying to make draggable gameobjects in Unity and right now I've got it so it follows the mouse.

It's not exactly what I need, I want it to move by 0.375f in the mouse direction instead of going exactly where the mouse is.

I can't really imagine how would it work - any help would be appreciated! This is what I've got so far:

    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(transform.parent.position);
        offset = transform.parent.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 curScreenPt = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPos = Camera.main.ScreenToWorldPoint(curScreenPt) + offset;
        transform.parent.position = new Vector3(curPos.x, curPos.y);
    }
  • Important: it's nowadays INCREDIBLY EASY to implement drag and drop and similar concepts in Unity. Here: http://stackoverflow.com/a/37473953/294884 – Fattie Nov 20 '16 at 17:19
  • Yeah, but afaik it's UI - only, I'm working on game objects so it doesn't really work –  Nov 20 '16 at 20:32

1 Answers1

2

Nevermind, I'm dumb.

void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(transform.parent.position);
    offset = transform.parent.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

void OnMouseDrag()
{
    Vector3 curScreenPt = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 curPos = Camera.main.ScreenToWorldPoint(curScreenPt) + offset;
    transform.parent.position = new Vector3(Mathf.Round(curPos.x/0.3175f) * 0.3175f, Mathf.Round(curPos.y / 0.3175f) * 0.3175f);
}