# [Solved]Drag a gameObject problem

I have a simple script that moves a gameObject across the screen when you drag it. The problem is that it moves the gameObject to the target position even when I click. I’m trying to figure out how to make it move only when I drag.
Here’s my code :

``````void OnMouseDrag()
{

Vector3 screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

Vector3 curMousePosition = Camera.main.ScreenToWorldPoint(curScreenPoint);

// Lerp the gameObjects position
transform.position = Vector3.Lerp(transform.position,curMousePosition,Time.deltaTime * 2.0f);

}
``````

Any help would be awesome.

It’s called every frame the mouse button is down so the behavior you’re seeing would be expected. My guess is that you’ll want to set some kind of threshold for how far the player needs to move the mouse to start dragging.

Also - using Lerp with Time.deltaTime like that isn’t correct.

Thanks for the suggestion. By setting a threshold, do you mean doing something like this :

``````if(Input.mousePosition.x > 1 || Input.mousePosition.y > 1){
//Drag
}
``````

How do I use Time.deltaTime with Lerp correctly? It seems to be working fine at the moment.

You don’t The final argument in Lerp is meant to be a “percentage of completion” where 0 is …0 and 1 is 100 (ie the lower bound or the upper bound passed to Lerp). So you’re basically passing some really small number (under 1% “completion”) to it every time.

If I did

``````float i = Mathf.Lerp(0, 1, Time.deltaTime);
``````

I would get some small decimal number back every time.

If I wanted to move from 0 to 1 in 2 seconds I could do something like this

``````totalTime += Time.deltaTime;
float i = Mathf.Lerp(0, 1, totalTime / 2f);
``````

In terms of threshold you need to store where the player clicked and compare the distance between that and where the cursor is this frame.

Oh, I never knew that about Lerp. Thanks for letting me know

I’ll try setting a threshold like that and see how it goes.

Figured it out! Looks like someone had the same problem before and solved it here.

``````private Vector3 screenPoint;
private 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()
{

screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

Vector3 curMousePosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;

transform.position = Vector3.Lerp(transform.position,curMousePosition,Time.deltaTime * 2.0f);

}
``````