drag rigibody2d object

Hello,

I have made a script (after ton of hours of search) who allow to move object with mouse from 2D scene. This script grab all item on the scene, how to select just one item ? I have tested lot of script and nothing work. Any idea ?

#pragma strict

private var bouton : boolean;

function FixedUpdate () 
{
}	

function Update () 
{
	if (Input.GetButtonDown("Fire1")) 
	{

		bouton = true;	
	}
	else if (Input.GetButtonUp("Fire1"))
	{
	    bouton = false;
	}    	
	if (bouton)
	{ 
		var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
		if(hit.collider != null)
		{
			var mousePos = Input.mousePosition;
			var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, mousePos.y,16));
			transform.position  = wantedPos;
		}
	}
}

Quick response

To fix that, you only need to change transform.position = wantedPos;

into hit.collider.gameObject.transform.position = wantedPos;

Explanation

If you attach this script to all your game objects, it is obvious that all of them get grabbed, because transform.position = wantedPos; changes the position of the game object which have this script as a component.

To avoid such a problem, you should specify that the game object which you want to grab is the one which the collider is hit by the RaycastHit2D.

Oh that is working but new trouble when I move object after some distance the object is released. Any idea ?

hit.transform.position = wantedPos; to move the object rather than yourself, and…

You are using Input.GetMouseButtonDown, which only returns once; the frame your mouse clicks. Use:

if(Input.GetButton("Fire1"))
    bouton = true;
else
    bouton = false;