- Home /
How to click and drag Game Objects?
I am making a game that involves the player clicking and dragging game objects across the scene.
This is what i am trying.
public class Drag : MonoBehaviour {
private Vector3 screenPoint;
private Vector3 offset;
void Start () {
}
void Update () {
}
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(Input.mousePosition);
offset = Input.mousePosition - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
but whenever i click on the object, it jumps out of the camera view. If i drag while pressing the mouse button , the object moves with it. I can see in the inspector, but is is out of the camera view. Can somebody help me with this? Thanks in advance
Answer by Mayank Ghanshala · Dec 31, 2014 at 12:37 PM
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(Input.mousePosition);
offset = Input.mousePosition - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
Still same problem. I displayed the mouseposition too. Those coordinates are out if the camera view too. But, that should not be the case.
offset = Input.mousePosition - Camera.main.ScreenToWorldPoint
this part doesnt make any sense to me, you compare a point on the screen to a point in the world which is 2 entierly separate type of numbers.
public class Drag : $$anonymous$$onoBehaviour { private Vector3 screenPoint; private Vector3 offset;
void Start () {
}
void Update () {
}
void On$$anonymous$$ouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,screenPoint.z));
}
void On$$anonymous$$ouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
} This is the solution if anyones needs it. just add this to the gameobject and tada!! you can now drag a gameobject without it lagging behind the mouse pointer.
Thank you for posting your solution! Really helped me out.
Answer by daipayan123 · Dec 31, 2014 at 06:37 PM
I solved it, thanks. Only have to manage the lag of the object from the mouse ppointer. Any tips?