Search Unity

Question Camera movement: pan, zoom and rotate

Discussion in 'Getting Started' started by ABB13, May 26, 2022.

  1. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    82
    Hello everyone,
    I'm trying to create a camera controller similar like the Blender navigation camera, so the camera will panning in the space with the click of mouse, will rotate on click of the mouse and zoom toward the mouse.

    I'm trying to create it for days, but I can't figure it out how to do it. Can anyone help me?
     
  2. Mortichar

    Mortichar

    Joined:
    Mar 30, 2017
    Posts:
    19
    Personally, I think the easiest way to think of most of these operations is in terms of the camera's transform's forward, up, and right vectors.

    To move the camera forward and backwards, you add or subtract its forward vector from its position. To move left or right, you add or subtract the right vector. To move up or down, you add or subtract the up vector. To rotate (roll) the camera, you want to rotate it around the forward vector.

    Most of these operations are as simple as something along the lines of

    Code (CSharp):
    1.  
    2. // for moving the camera forward and backwards (what I believe you referred to as zooming, but zooming is actually changing the field of view)
    3. camera.transform.position += camera.transform.forward * Time.deltaTime * someScaleFactor;
     
    ABB13 likes this.
  3. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    82

    Thanke you for your reply, I'm tried to follow your advice writing this code for right and left movement:
    Code (CSharp):
    1. if (InputMouse.MiddletMouseButtonJustClicked)
    2.         {
    3.             _startPosition = GetWorldPosition(_groundZ);
    4.         }
    5.  
    6.         if (InputMouse.MiddleMouseButtonPressed)
    7.         {
    8.             Vector3 distance = _startPosition - GetWorldPosition(_groundZ);
    9.             Camera.main.transform.position += (Camera.main.transform.right + distance);
    10.         }
    and doesn't go very well: it work not bad when I'm at (0,0,0) rotation of the camera, but if I rotate the camera it will works really bad