- Home /
Hand tool on a 2D plane
Hello, I'm trying to do a simple 2D "hand tool". I got it working but I accidentally deleted something I thought was obsolete. As it turns out, my first try was a stroke of luck, since I haven't been able to make it work again.
I experience a bug where the camera flickers when i try to drag. I'm sure I'm not the first person to do a drag script (maybe the biggest n00b tho), but i cannot find any other documentation on this. Any input would be appreciated.
//SCROLL var camCurrent : Vector3; //static camera position var pressedPosDif : Vector3; // difference between pressed and moved var pressedPos: Vector3; //starting coordinates for button hold var pressed:boolean = false; //is the button held?
//INITIATE function Start(){ camCurrent=camera.main.transform.position; }
//UPDATE
function Update () { if (Input.GetMouseButtonDown(0)) { pressedPos = (Camera.main.ScreenToWorldPoint(Input.mousePosition)); pressed = true; mouseCheck(); } }
function mouseCheck () { while (pressed) { pressedPosDif=pressedPos-(Camera.main.ScreenToWorldPoint(Input.mousePosition)); Camera.main.transform.position=camCurrent+pressedPosDif; yield; if (Input.GetMouseButtonUp(0)) { camCurrent=Camera.main.transform.position; pressed = false; } } }
Answer by skovacs1 · Nov 15, 2010 at 03:37 PM
This seems like more work than you need.
Why not do something like:
MouseTranslate.js (Attached to the camera)
var scale : float = 0.2f
function Update() {
if(Input.GetMouseButton(0)) {
transform.position -= transform.right * Input.GetAxis("Mouse X") * scale;
transform.position -= transform.up * Input.GetAxis("Mouse Y") * scale;
}
}
For more precise movement, you could do some screen point converson:
MouseDragPosition.js (Attached to the camera)
var planeDistance : float = 10.0f;
private var dragPoint : Vector3 = Vector3.zero;
function Update() {
var screenPoint : Vector3 = camera.ScreenToWorldPoint(Vector3(
Input.mousePosition.x,
Input.mousePosition.y,
planeDistance));
if(Input.GetMouseButtonDown(0)) dragPoint = screenPoint;
else if(Input.GetMouseButton(0)) transform.position += dragPoint-screenPoint;
}
Hey thanks, for the answer, wasn't quite what I was looking for since it creates a "sliding" effect unlike the standard hand tool. Thanks for the effort though
You're concerned about 1:1-ish movement then? The Unity editor's hand tool is also subject to "sliding" as you call it, the further you move away. To mimic Unity's editor's hand tool more closely, you would simply a) subtract the movement ins$$anonymous$$d of add and multiply the movement by some factor which you can play with as you like. I find 0.2f works nicely for objects 5 units in front of the camera. If you want/need more precise movement, you could do some calculation with the world point of the mouse position. Code to come.
Your answer
![](https://koobas.hobune.stream/wayback/20220613083043im_/https://answers.unity.com/themes/thub/images/avi.jpg)