- Home /
Drag GameObject with mouse in just one axis
Hello Unity fellows, I have a simple doubt, and already saw all the threads with the 'mouse' tag and cant find the answer. Here is my problem: I need to move one gameobject with the mousedrag operation, and i just want to move it in one specific direction. Some objects ill have to be moved in the Z axis, others in the X. But none in the Y. My game is a 3D Game, and the camera ill look like this: http://i53.tinypic.com/2r76e6o.jpg The camera ill be freezed, the only thing that ill move are these gameobjects. Here is an example of how i want to move the objects: http://i51.tinypic.com/2h7hpj7.jpg
Can anyone help me with tips or even a finished script ? Im making this game for a college project, so i dont have too many time to study programing (im a 3d modeler), but i can try some basic stuff ;) Sry my bad english too! Thanks in advance.
Answer by Syksy · Jan 15, 2012 at 12:35 AM
Hello,
Below's a (java) script I used for moving gameObjects in just X-axis direction:
function OnMouseDrag()
{
point = Camera.main.ScreenToWorldPoint(
Vector3(
Input.mousePosition.x,
(transform.position.y-Camera.main.transform.position.y),
(transform.position.z-Camera.main.transform.position.z)));
point.y = transform.position.y;
point.z = transform.position.z;
transform.position = point;
}
Hope this is of assistance. I'm using a 2d orthographic camera and this solution works for my game - I'm not an experienced programmer either, but this approach could be used to also move items in Z-axis direction I believe.
what if i want to move it up down left and right .. ? thx !
Following the above example and assu$$anonymous$$g you mean you want to drag an object in x- and y-axis directions (while keeping z fixed), the script would be:
function On$$anonymous$$ouseDrag() { point = Camera.main.ScreenToWorldPoint( Vector3( Input.mousePosition.x, Input.mousePosition.y, (transform.position.z-Camera.main.transform.position.z)));
point.z = transform.position.z; transform.position = point; }
If you found the solution helpful please vote :)