- Home /
Question by
Johnz1234 · Jun 18, 2015 at 10:59 AM ·
scriptingbasics
Dragg 2D object?
how can i drag this object only in x axis or y :D private Vector3 handleToOriginVector; public bool isDragging;
void OnMouseDown () {
handleToOriginVector = transform.root.position - Camera.main.ScreenToWorldPoint (Input.mousePosition);
isDragging = true;
}
void OnMouseDrag () {
transform.root.position = Camera.main.ScreenToWorldPoint (Input.mousePosition) + handleToOriginVector;
}
void OnMouseUp () {
isDragging = false;
}
Comment
If want to drag in x-axis only, then change transform.root.position.x variable only. Same with handleToOriginVector.x and everything else.
Same logic will follow dragging along y-axis.
Best Answer
Answer by alok-kr-029 · Jun 18, 2015 at 11:14 AM
you want to drag an object in x or y axis
x axis
void OnMouseDrag () {
Vector3 vec =Camera.main.ScreenToWorldPoint (Input.mousePosition) ;
transform,position = new Vector3(vec.x, transform.position.y,transform.position.z);
}
y axis
void OnMouseDrag () {
Vector3 vec =Camera.main.ScreenToWorldPoint (Input.mousePosition) ;
transform,position = new Vector3( transform.position.x,vec.y,transform.position.z);
}
you can add your handleToOriginVector
hope this will work