Smooth Drag and drop in Unity3D

Advertisemen

If any of you guys have realised that when you use drag and drop script, I previously posted here - Drag and Drop in Unity3D, gameObject jumps to the mouse position, it means when you click on the centre point of object there is no problem but when you click on the side of object, it jumps and try to match mouse position with centre point of itself.
So let's see how to fix that problem. add the following highlighted codes in your previous codes.

float distX;
float distY;
void OnMouseDown(){
        screenPoint =    Camera.main.WorldToScreenPoint(transform.position);

        distX = Input.mousePosition.x - screenPoint.x;

      distY = Input.mousePosition.y - screenPoint.y;
    }
 
void OnMouseDrag(){
            Vector3 currentScreenPoint = new Vector3(Input.mousePosition.x - distX, Input.mousePosition.y - distY, screenPoint.z);

            Vector3 currentPos = Camera.main.ScreenToWorldPoint(currentScreenPoint);

}

Now try to drag and drop.It is smooth.
            transform.position = currentPos;
        }
    }

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D