# Object dragging at manual point

For my 2d game, I want to drag object in horizontal direction.

For dragging, I have used following code.

``````private bool isTouchDown;

void Update ()
{
if (Input.GetMouseButtonDown(0)) {
Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (pos, Vector2.zero);
if (hit != null && hit.collider != null && hit.collider.CompareTag(Constants.TAG_PLAYER_PADDLE))
isTouchDown=true;

}else if(Input.GetMouseButtonUp(0))
isTouchDown=false;

if(isTouchDown){
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
touchPosition.y = -8f;
touchPosition.z = -1;
touchPosition.x  = Mathf.Clamp(touchPosition.x,-3.5f,3.5f);
transform.position = touchPosition;
}
}
``````

By default object dragged from centre. That point I want to change.
If player touch object from corner then object gets dragged from that point not centre one.

I know I have to use some math here but at present I can’t able to calculate it.
Please provide some guidance in this.

You can try something like that…

``````private bool dragging = false;
private float distance;
void OnMouseDown()
{
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}

void OnMouseUp()
{
dragging = false;
}
void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);   //
rayPoint.y = -8f;
rayPoint.z = -1f;
transform.position = rayPoint;
}
}
``````

i’m using soemthing similar for my projects and works like a cake!

I have found solution for this problem. Here I posted it to help other members.

``````private bool isTouchDown;
private float xOffset;

void Update ()
{
if (Input.GetMouseButtonDown (0)) {
Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (pos, Vector2.zero);
if (hit != null && hit.collider != null && hit.collider.CompareTag (Constants.TAG_PLAYER_PADDLE)) {
isTouchDown = true;
Vector3 touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
xOffset = transform.position.x - touchPosition.x;
}

} else if (Input.GetMouseButtonUp (0))
isTouchDown = false;

if (isTouchDown) {
Vector3 touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
touchPosition.y = -8f;
touchPosition.z = -1;
touchPosition.x += xOffset;
touchPosition.x = Mathf.Clamp (touchPosition.x, -3.5f, 3.5f);
transform.position = touchPosition;
}
}
``````

Now I can able to drag game object from any point in horizontal direction.