How to move camera by "grabbing" ground and moving mouse

I want to grab my terrain and move the camera with my mouse, this was fairly simple to do using speed:

newPosition = transform.position; //Set in Start
//...

// In update
newPosition -= new Vector3(Input.GetAxis("Mouse X") * cameraDragSpeed, 0, Input.GetAxis("Mouse Y") * cameraDragSpeed);
transform.position = Vector3.Lerp(transform.position, newPosition, GameManager.Instance.GetNormalizedTimescale() * acceleration);

But I dont want to use speed, I want to use the difference between the drag origin (or the last drag position) and the new drag position.

I got some code running that oddly work “kind of” well, but has periods where it starts acting rly strangly, like the camera will keep panning while I hold down my button, even tho im not moving the mouse. But it happens very randomly. Or sometimes the drag speed is really responsive but other times its like im dragging in mud.

// In update
// Drag movement
            if (Input.GetMouseButtonDown(1))
            {
                cameraMovementDragOrigin = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
            }
            else if (Input.GetMouseButton(1))
            {
                var diff = cameraMovementDragOrigin - new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
                newPosition += new Vector3(diff.x, 0, diff.y);
                transform.position = newPosition;
                return;
            }

Can someone spot what im doing wrong?

That’s how I’m doing it. Here is my world-dragger:

https://github.com/kurtdekker/proximity_buttons/blob/master/proximity_buttons/Assets/DemoWorldDragging/SimpleCameraDrag.cs

Full setup scenes available right in that same folder: one to drag arbitrary items in scene, one to drag the ground and cause the camera to move in reverse.

Not until those hairy long lines of code are broken down into single-step operations, plus the duplication of reading mouse in 5 places isn’t great either.

Referencing my linked code example above;

  • mouse input is read on line 21 into touch (from my MicroTouch combiner class, merely to use mouse / touch code identically)

  • position is read and converted in line 23

  • click is sensed on line 33

  • delta is computed once on line 40

  • delta is applied once on line 46

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

1 Like