- Home /
Need help calculating offset when dragging an object 2D
So I am able to drag this 2D object, but the gameobject's origin goes to the ray and I am unsure of how to calculate the offset so it doesn't set the position to the origin.
if(Input.GetKey(KeyCode.Mouse0))
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null) //checks if reference is null or not | this eliminated the null reference error
{
if(hit.collider.tag == "PointA")
{
//Debug.Log ("Hit");
hit.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f));
}
}
}
Answer by robertbu · May 16, 2014 at 02:40 PM
Calculate the offset on the mouse down. It will be:
var offset = hit.transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
offset.z = 0.0;
Then you can just add the offset back in when you position the item. Note doing your drag your current code will will have an issue. If the mouse leaves the collider of the dragged object (easy to do if the mouse is moving quickly), the dragging stops. It might be better to record the transform of the object to be dragged in mouse down, and then just drag the recorded transform during mouse movement.
Note I've never seen GetKey() used to get the mouse, but apparently it works. Typically Input.GetMouseButtonDown(0) is used.