Skip to main content
3 of 3
Simplifying
DMGregory
  • 140.8k
  • 23
  • 257
  • 401

Let's do some algebra! You have three equations like this:

difference = mouseWorldPosition - oldCameraWorldPosition

origin = mouseWorldPosition

newCameraWorldPosition = origin - difference

We can substitute the definitions for origin and difference into the last equation and simplify:

newCameraWorldPosition = (mouseWorldPosition) - (mouseWorldPosition - oldCameraWorldPosition)
newCameraWorldPosition = mouseWorldPosition - mouseWorldPosition + oldCameraWorldPosition
newCameraWorldPosition = oldCameraWorldPosition

Congratulations. You've told the camera "stay where you were" with extra steps. 😜

You probably want something more like this:

Vector3 GetMousePositionInWorld() {
    Vector3 screenPosition = Mouse.current.position.ReadValue();

    // If you're using a perspective camera for parallax, 
    // be sure to assign a depth to this point.
    // screenPosition.z = 1f;

    return mainCamera.ScreenToWorldPoint(screenPosition);
);


private IEnumerator DragCameraUpdate()
{
    Vector3 initialMousePosition = GetMousePositionInWorld();

    while (mouseClick.ReadValue<float>() != 0)
    {
        Vector3 currentMousePosition = GetMousePositionInWorld();
        Vector3 travel = currentMousePosition - initialMousePosition;
        
        // Remove any vertical travel to lock the motion to the horizontal plane.
        travel.y = 0;

        mainCamera.transform.Translate(-travel, Space.World);

        yield return null;
    }
}
DMGregory
  • 140.8k
  • 23
  • 257
  • 401