the object which move by mouse overlap

i write a script to control object by mouse movement ( hold mouse(0) to activate object and move it),but when i move the object, it will overlap other object in the sence.
how can i keep object out of the collider of the other object?

the script:

var time : int = 0;

private var isCanMove    : boolean = false;
private var defaultColor : Color;


function Start()
{
  defaultColor = renderer.material.color;
}

function OnMouseDrag ()
{
    time ++;        
    if( time == 50 )
    {
       renderer.material.color = Color.red;       
       isCanMove = true;
    }    
     if( isCanMove )
   {
     var screenSpace = Camera.main.WorldToScreenPoint( transform.position );
     var offset = transform.position - Camera.main.ScreenToWorldPoint( Vector3( Input.mousePosition.x, Input.mousePosition.y, screenSpace.z ) );
     while ( Input.GetMouseButton( 0 ) )
     {
         var curScreenSpace = Vector3( Input.mousePosition.x, Input.mousePosition.y, screenSpace.z );
         var curPosition = Camera.main.ScreenToWorldPoint( curScreenSpace ) + offset;
         transform.position = curPosition;
         yield;
     }
   }       

}

// when mouse up, object can't move

function OnMouseUp ()
{
    renderer.material.color = defaultColor;
    isCanMove = false;
    time = 0;
}

thank you for your help!

  1. Attach a rigidbody to the object (if you have not already).
  2. Use rigidbody.MovePosition instead of transform.position.
  3. If possible you should only move stuff in “void FixedUpdate (){ }”

What this does is telling the physics engine to move the object instead of you directly moving the object.

There is also a ‘DragRigidBody’-script included in the standard assets if you need any more help (or just want to use that):
Assets → Import Package → Scripts. Import