Eliminate Z movement

I’m trying to let the user move a game object (in this case a cube) with the mouse. I only want it to move in the X or Y axes.

There are several good scripts doing this posted around the forums, including the one from Carsten and the one from giza/rmlloyd. Carsten’s limits movement Y movement but I haven’t figured out to switch it to limit Z movement.

Is there some way I can just tell the cube that it simply can’t move in the Z axis? If I could, then either Carsten’s or giza/rmlloyd’s scripts would work beautifully.

Any help is appreciated.

Try this:

var depth = 0.0;

function Update ()
{
     transform.position.z = depth;
}

Thanks, Daniel.

I’ve tried that but the object just disappears from view (it’s still out there, it’s just blow very far off screen in the Y position).

Here’s the core of the code from rmlloyd/giza which seems to work except that it allows movement in the Z axis. What can I change to eliminate this?

var curPos =0;
var curScreenPos : Vector3;

function OnMouseDown () { 
   var screenPos = Camera.main.WorldToScreenPoint(transform.position);  
   while (Input.GetMouseButton(0)) 
   { 
      var curScreenPos = Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z); 
      var curPos = Camera.main.ScreenToWorldPoint(curScreenPos); 
      transform.position = curPos; 
      yield; 
        
   } 
}

If all you want to do is move the object restrained to the x/y plane then something like the following would probably work fine. However, it assumes you want no constraints on the movement and also don’t wish for it to collide with anything. Such as a fancy 3d reticle for a game like missile command.

   var x = Input.mousePosition.x; 
   var y = Input.mousePosition.y;
   var z = transform.position.z;
   var localCam = camera.main; 

 // Move the object
      transform.position = localCam.ScreenToWorldPoint (Vector3 (x, y, z));

If you want constraints, clamping the movement based upon screen size with Mathf.Clamp might work for you.

If you want collision I’ve found two examples. The first being the dragrigidbody script included with Unity, which seems to attach a physics based spring joint between the mouse cursor and the object. The other is a script on the wiki which does something similar, but calculates the physical forces itself, to move the object from point a to point b.