Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

How to make camera move in a way similar to editor scene?

Discussion in 'Scripting' started by Xhitman, Apr 2, 2018.

  1. Xhitman

    Xhitman

    Joined:
    Oct 30, 2015
    Posts:
    452
    Code (CSharp):
    1.  // Zoom
    2.         if (Input.mouseScrollDelta == Vector2.down)
    3.             Camera.main.orthographicSize += 5;
    4.         else if (Input.mouseScrollDelta == Vector2.up)
    5.             Camera.main.orthographicSize -= 5;
    6.  
    7.         if (Camera.main.orthographicSize < 5)
    8.             Camera.main.orthographicSize = 5;
    9.         else if (Camera.main.orthographicSize > 200)
    10.             Camera.main.orthographicSize = 200;
    11.                
    12.         // rotate left/right, up/down
    13.         if (Input.GetMouseButton(1))
    14.         {
    15.             cameraHolder.Rotate(Vector3.up * Input.GetAxisRaw("Mouse X") * cameraRotateSpeed, Space.Self);
    16.             Camera.main.transform.Rotate(Vector3.right * Input.GetAxisRaw("Mouse Y") * cameraRotateSpeed, Space.Self);
    17.         }
    18.  
    19.         // Move
    20.         if (Input.GetMouseButton(2))
    21.         {
    22.             cameraHolder.position += new Vector3(Input.GetAxisRaw("Mouse X") * cameraMoveSpeed, 0, Input.GetAxisRaw("Mouse Y") * cameraMoveSpeed);
    23.            
    24.         }
    The move part is not correct, i don't know the scene camera movement refer to, basically adding x,z based on the world axis do not work.
     
  2. Xhitman

    Xhitman

    Joined:
    Oct 30, 2015
    Posts:
    452
    Code (CSharp):
    1. // Move,  Z use camera forward project vector, X use camera right
    2.          if (Input.GetMouseButton(2))
    3.          {
    4.              Vector3 projectVector = Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up);
    5.              cameraHolder.Translate(projectVector* Input.GetAxisRaw("Mouse Y") * cameraMoveSpeed, Space.World);
    6.              cameraHolder.Translate(Camera.main.transform.right * Input.GetAxisRaw("Mouse X") * cameraMoveSpeed, Space.World);
    7.          }
    Finally, make the camera exactly same as the editor
     
  3. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,920
    Something like this will give WASD control relative to camera:

    Script should go on camera gameobject.
    Code (csharp):
    1.    void Update()
    2.    {
    3.         float h = Input.GetAxis("Horizontal");
    4.         float v = Input.GetAxis("Vertical");
    5.  
    6.         Vector3 right = transform.right * h * Time.deltaTime;
    7.         Vector3 forward = transform.forward * v * Time.deltaTime;
    8.  
    9.         transform.Translate(right + forward);
    10.     }
     
  4. Mokzen

    Mokzen

    Joined:
    Oct 10, 2016
    Posts:
    102
  5. The_Pied_Shadow

    The_Pied_Shadow

    Joined:
    Jul 25, 2018
    Posts:
    14
    This thread is a bit old at this point but I came across it trying to find out how to make camera movement that worked like the camera in the editor window. I didn't find the answers here helpful to me but I did eventually manage to make a script that does it so I wanted to share it here in case someone else comes across it.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CameraController : MonoBehaviour
    4. {
    5.     [SerializeField] float speed = 0.5f;
    6.     [SerializeField] float sensitivity = 1.0f;
    7.  
    8.     Camera cam;
    9.     Vector3 anchorPoint;
    10.     Quaternion anchorRot;
    11.  
    12.     private void Awake()
    13.     {
    14.         cam = GetComponent<Camera>();
    15.     }
    16.    
    17.     void FixedUpdate()
    18.     {
    19.         Vector3 move = Vector3.zero;
    20.         if(Input.GetKey(KeyCode.W))
    21.             move += Vector3.forward * speed;
    22.         if (Input.GetKey(KeyCode.S))
    23.             move -= Vector3.forward * speed;
    24.         if (Input.GetKey(KeyCode.D))
    25.             move += Vector3.right * speed;
    26.         if (Input.GetKey(KeyCode.A))
    27.             move -= Vector3.right * speed;
    28.         if (Input.GetKey(KeyCode.E))
    29.             move += Vector3.up * speed;
    30.         if (Input.GetKey(KeyCode.Q))
    31.             move -= Vector3.up * speed;
    32.         transform.Translate(move);
    33.  
    34.         if (Input.GetMouseButtonDown(1))
    35.         {
    36.             anchorPoint = new Vector3(Input.mousePosition.y, -Input.mousePosition.x);
    37.             anchorRot = transform.rotation;
    38.         }
    39.         if (Input.GetMouseButton(1))
    40.         {
    41.             Quaternion rot = anchorRot;
    42.             Vector3 dif = anchorPoint - new Vector3(Input.mousePosition.y, -Input.mousePosition.x);
    43.             rot.eulerAngles += dif * sensitivity;
    44.             transform.rotation = rot;
    45.         }
    46.     }
    47. }
    This script attached to my camera object got me what I wanted.
     
    YZ001, radiantboy, kubpica and 3 others like this.
  6. StuwuStudio

    StuwuStudio

    Joined:
    Feb 4, 2015
    Posts:
    165
    Here's something to remember: NEVER use GetInputDown/Up in the fixed loop. They won't be called properly. On top of that, running movement stuff in the fixed loop (unless you have interpolation) will just make the camera jittery if you're used to playing at 60 fps.

    Here's my modified version with a little more accurate sensitivity and speed. Note that the speed parameters correspond to the speed parameters of the true camera editor.

    I might add camera acceleration and easing later.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CameraController : MonoBehaviour {
    4.     [SerializeField] float navigationSpeed = 2.4f;
    5.     [SerializeField] float shiftMultiplier = 2f;
    6.     [SerializeField] float sensitivity = 1.0f;
    7.  
    8.     private Camera cam;
    9.     private Vector3 anchorPoint;
    10.     private Quaternion anchorRot;
    11.  
    12.     private void Awake () {
    13.         cam = GetComponent<Camera>();
    14.     }
    15.  
    16.     void Update () {
    17.         if(Input.GetMouseButton(1)) {
    18.             Vector3 move = Vector3.zero;
    19.             float speed = navigationSpeed * (Input.GetKey(KeyCode.LeftShift) ? shiftMultiplier : 1f) * Time.deltaTime * 9.1f;
    20.             if(Input.GetKey(KeyCode.W))
    21.                 move += Vector3.forward * speed;
    22.             if(Input.GetKey(KeyCode.S))
    23.                 move -= Vector3.forward * speed;
    24.             if(Input.GetKey(KeyCode.D))
    25.                 move += Vector3.right * speed;
    26.             if(Input.GetKey(KeyCode.A))
    27.                 move -= Vector3.right * speed;
    28.             if(Input.GetKey(KeyCode.E))
    29.                 move += Vector3.up * speed;
    30.             if(Input.GetKey(KeyCode.Q))
    31.                 move -= Vector3.up * speed;
    32.             transform.Translate(move);
    33.         }
    34.  
    35.         if(Input.GetMouseButtonDown(1)) {
    36.             anchorPoint = new Vector3(Input.mousePosition.y, -Input.mousePosition.x);
    37.             anchorRot = transform.rotation;
    38.         }
    39.         if(Input.GetMouseButton(1)) {
    40.             Quaternion rot = anchorRot;
    41.  
    42.             Vector3 dif = anchorPoint - new Vector3(Input.mousePosition.y, -Input.mousePosition.x);
    43.             rot.eulerAngles += dif * sensitivity;
    44.             transform.rotation = rot;
    45.         }
    46.     }
    47. }
     
    The_Pied_Shadow and zanouk like this.
  7. CowMan9999

    CowMan9999

    Joined:
    Jan 12, 2021
    Posts:
    2
    I'm New And Want To use This, But I'm Just Wondering...
    Do You Need To Use Time.deltaTime For This? ;)
     
  8. StuwuStudio

    StuwuStudio

    Joined:
    Feb 4, 2015
    Posts:
    165
    Yes you do.
    If you want a smooth camera, you must have run all your camera translation/rotation as many times as your scene gets redrawn. But if you remove that Time.delta time, your motion will get tied to your framerate, ex: if you spawn tons of objects in your scene and your frame rate cuts from 120 to 60, your editor camera would do the same amount of translation but x0.5 often, meaning you would move x0.5 slower.
     
  9. CowMan9999

    CowMan9999

    Joined:
    Jan 12, 2021
    Posts:
    2
    Thanks! Good To Know
     
  10. JFR

    JFR

    Joined:
    Feb 21, 2014
    Posts:
    65
    What does the *9.1f stand for in your speed calculation? Works great by the way.
     
  11. StuwuStudio

    StuwuStudio

    Joined:
    Feb 4, 2015
    Posts:
    165
    I forgot to reply, but I have honestly no idea, you could just remove it and multiply your navigation by it.
     
  12. grimmy

    grimmy

    Joined:
    Feb 2, 2009
    Posts:
    409
    Thanks for this. I took the liberty of adding mouse panning and mouse zoom (with shift speed modifier) with the middle mouse button. (Just like in the Unity editor :))

    Code (CSharp):
    1. using UnityEngine;
    2. public class CameraController : MonoBehaviour {
    3.     [SerializeField] float navigationSpeed = 2.4f;
    4.     [SerializeField] float shiftMultiplier = 2f;
    5.     [SerializeField] float sensitivity = 1.0f;
    6.     [SerializeField] float panSensitivity = 0.5f;
    7.     [SerializeField] float mouseWheelZoomSpeed = 1.0f;
    8.     private Camera cam;
    9.     private Vector3 anchorPoint;
    10.     private Quaternion anchorRot;
    11.  
    12.     private bool isPanning;
    13.     private void Awake () {
    14.         cam = GetComponent<Camera>();
    15.     }
    16.     void Update () {
    17.    
    18.    
    19.         MousePanning();
    20.         if(isPanning)
    21.         {return;}
    22.    
    23.         if(Input.GetMouseButton(1)) {
    24.             Vector3 move = Vector3.zero;
    25.             float speed = navigationSpeed * (Input.GetKey(KeyCode.LeftShift) ? shiftMultiplier : 1f) * Time.deltaTime * 9.1f;
    26.             if(Input.GetKey(KeyCode.W))
    27.                 move += Vector3.forward * speed;
    28.             if(Input.GetKey(KeyCode.S))
    29.                 move -= Vector3.forward * speed;
    30.             if(Input.GetKey(KeyCode.D))
    31.                 move += Vector3.right * speed;
    32.             if(Input.GetKey(KeyCode.A))
    33.                 move -= Vector3.right * speed;
    34.             if(Input.GetKey(KeyCode.E))
    35.                 move += Vector3.up * speed;
    36.             if(Input.GetKey(KeyCode.Q))
    37.                 move -= Vector3.up * speed;
    38.             transform.Translate(move);
    39.         }
    40.         if(Input.GetMouseButtonDown(1)) {
    41.             anchorPoint = new Vector3(Input.mousePosition.y, -Input.mousePosition.x);
    42.             anchorRot = transform.rotation;
    43.         }
    44.    
    45.         if(Input.GetMouseButton(1)) {
    46.             Quaternion rot = anchorRot;
    47.             Vector3 dif = anchorPoint - new Vector3(Input.mousePosition.y, -Input.mousePosition.x);
    48.             rot.eulerAngles += dif * sensitivity;
    49.             transform.rotation = rot;
    50.         }
    51.  
    52.         MouseWheeling();
    53.    
    54.     }
    55.  
    56.     //Zoom with mouse wheel
    57.     void MouseWheeling()
    58.     {
    59.         float speed = 10*(mouseWheelZoomSpeed * (Input.GetKey(KeyCode.LeftShift) ? shiftMultiplier : 1f) * Time.deltaTime * 9.1f);
    60.        
    61.         Vector3 pos = transform.position;
    62.         if (Input.GetAxis("Mouse ScrollWheel") < 0)
    63.         {
    64.             pos = pos - (transform.forward*speed);
    65.             transform.position = pos;
    66.         }
    67.         if (Input.GetAxis("Mouse ScrollWheel") > 0)
    68.         {
    69.             pos = pos + (transform.forward*speed);
    70.             transform.position = pos;
    71.         }
    72.     }
    73.  
    74.  
    75.     private float pan_x;
    76.     private float pan_y;
    77.     private Vector3 panComplete;
    78.  
    79.     void MousePanning()
    80.     {
    81.    
    82.         pan_x=-Input.GetAxis("Mouse X")*panSensitivity;
    83.         pan_y=-Input.GetAxis("Mouse Y")*panSensitivity;
    84.         panComplete = new Vector3(pan_x,pan_y,0);
    85.    
    86.         if (Input.GetMouseButtonDown(2))
    87.         {
    88.             isPanning=true;
    89.         }
    90.    
    91.         if (Input.GetMouseButtonUp(2))
    92.         {
    93.             isPanning=false;
    94.         }
    95.    
    96.         if(isPanning)
    97.         {
    98.             transform.Translate(panComplete);
    99.         }
    100.    
    101.  
    102.     }
    103.  
    104. }
     
  13. StuwuStudio

    StuwuStudio

    Joined:
    Feb 4, 2015
    Posts:
    165
    Group effort!
     
    The_Pied_Shadow likes this.
  14. unity_7qf-V822dyI1aA

    unity_7qf-V822dyI1aA

    Joined:
    Jul 15, 2019
    Posts:
    2
    I was using your script and i couldn't figure out why when zooming in or out i was going throught layers intead or getting closer to object.
    If any one have the same problem
    make sure that the camera is on perspective projection mode and not orthographic
     
  15. Amalrajaaryan

    Amalrajaaryan

    Joined:
    Dec 19, 2020
    Posts:
    1
    If anyone still searching for one, then :
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CameraMovement : MonoBehaviour
    4. {
    5.      [Header("REFERENCES")]
    6.  
    7.      [Header("Camera")]
    8.      public Camera MainCamera;
    9.      [Range(0f,50f)]
    10.      public float CameraFocusPointDistance = 25f;
    11.  
    12.      [Header("SETTINGS")]
    13.  
    14.      [Space(2)]
    15.      [Header("Speed")]
    16.      [Range(0f,1f)]
    17.      [Tooltip("The Movement Speed of Camera")]
    18.      public float MovementSpeed;
    19.      [Range(0f,1f)]
    20.      [Tooltip("The On-Axis Rotation Speed of Camera")]
    21.      public float RotationSpeed;
    22.      [Range(0f,15f)]
    23.      [Tooltip("The Zoom speed of Camera")]
    24.      public float ZoomSpeed;
    25.      [Range(45f,450f)]
    26.      [Tooltip("The Revolution speed of Camera")]
    27.      public float RevolutionSpeed;
    28.  
    29.      [Space(2)]
    30.      [Header("Adjusting Values")]
    31.      [Range(0f,1f)]
    32.      [Tooltip("The amount the Movement speed will be affected by Zoom Input")]
    33.      public float ZoomInputAdjust = 1f;
    34.  
    35.  
    36.      //Internal Private Variables
    37.      private float ZoomInputIndex = 1f;
    38.      private RaycastHit hit; //For Storing Focus Point
    39.      void Update()
    40.      {
    41.           //Translation
    42.           float translateX = 0f;
    43.           float translateY = 0f;
    44.          
    45.           //Rotation
    46.           float rotationX = 0f;
    47.           float rotationY = 0f;
    48.  
    49.           float ZoomInput = Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
    50.           ZoomInputIndex += ZoomInput * ZoomInputAdjust;
    51.  
    52.           if(Input.GetMouseButton(0))
    53.           {
    54.                if(Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
    55.                {
    56.                     float revY = Input.GetAxis("Mouse Y");
    57.                     float revX = Input.GetAxis("Mouse X");
    58.  
    59.  
    60.                     transform.RotateAround(GetFocusPoint(), Vector3.up, revX * RevolutionSpeed * Time.deltaTime);
    61.                     transform.RotateAround(GetFocusPoint(), transform.right, -revY * RevolutionSpeed * Time.deltaTime);
    62.                }
    63.                else
    64.                {
    65.                     translateY = Input.GetAxis("Mouse Y") * (MovementSpeed/ZoomInputIndex);
    66.                     translateX = Input.GetAxis("Mouse X") * (MovementSpeed/ZoomInputIndex);
    67.                }
    68.           }
    69.           else if(Input.GetMouseButton(1))
    70.           {
    71.                rotationY = Input.GetAxis("Mouse Y") * RotationSpeed;
    72.                rotationX = Input.GetAxis("Mouse X") * RotationSpeed;
    73.           }
    74.          
    75.           transform.Translate(-translateX, -translateY, ZoomInput);
    76.           transform.Rotate(0, rotationX, 0, Space.World);
    77.           transform.Rotate(-rotationY, 0, 0 );
    78.      }
    79.  
    80.      private Vector3 GetFocusPoint()
    81.      {
    82.           if(Physics.Raycast(MainCamera.transform.position,MainCamera.transform.forward,out hit,CameraFocusPointDistance))
    83.           {
    84.                return hit.point;
    85.           }
    86.           else
    87.           {
    88.                return MainCamera.transform.position + MainCamera.transform.forward * CameraFocusPointDistance;
    89.           }
    90.      }
    91.  
    92.      [ContextMenu("Auto Assign Variables")]
    93.      public void AutoSetup()
    94.      {
    95.           MainCamera = Camera.main;
    96.      }
    97. }
    Just paste it, assign the Camera or from the Context Menu click "Auto Assign Variables" and you're done.
    You can change values according to your preferences.

    Includes all controls of editor, focus point calculation, left click and drag to pan, scroll to zoom, right click to rotate on axis and left or right alt + left click to revolve around the focus point.
    It also changes and reduces movement speed based on the scroll to prevent large displacement of camera on zoomed in objects.