Question by
Richarrd82 · Feb 09, 2017 at 02:22 AM ·
2ddragdragging
Drag an object in one line
I am trying to make a draging effect. I have a project where u are supposed to pull a bone out of meat. The draging is working, but when i grab the bone i can move it in all directions. What i would like to achieve is that i can only drag it in one direction. On the images below i mean the red line. I tried many things but nothing worked so far. Any help is appreciated.
I used these functions for the draging
void OnMouseDown()
{
offset = this.transform.position - Camera.main.ScreenToWorldPoint(new Vector2(transform.position.x, Input.mousePosition.y));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector2(transform.position.x, Input.mousePosition.y);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
mountains-back.png
(49.8 kB)
Comment
Answer by StyleA77660 · Mar 01, 2018 at 05:12 AM
Maybe you can try transform.up, like this:
private Vector3 Offset;
private Vector3 MouseDownPosition;
void OnMouseDown()
{
Offset = this.transform.position;
MouseDownPosition = Input.mousePosition;
}
void OnMouseDrag()
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition - MouseDownPosition + new Vector3(0, Screen.height / 2f)).y * transform.up + Offset; //The coordinates are in 2d with (0,0) being the bottom-left.
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612110629im_/https://answers.unity.com/themes/thub/images/avi.jpg)