Search Unity

Simplle Free Fly Camera script

Discussion in 'Made With Unity' started by Marko-K135, Jan 24, 2013.

  1. Marko-K135

    Marko-K135

    Joined:
    Nov 23, 2012
    Posts:
    1
    Free Fly Cameras are useful for debugging and getting a better view of your game's map, as well as navigating to places that would be hard to reach without any hacks or debugging tools.

    I didn't find a good and easily customizable free fly camera script anywhere, so I made this one.
    It is very easy to use and customize.
    NOTE: This is to be used together with Unity's built-in Mouse Look script or equivalent, meaning this only manages the flying around.

    If you want the player to stay still and not react to input while you are in Free Fly mode, you can simply check for if its camera is enabled or not.

    you can use something like this example:
    Code (csharp):
    1.  
    2. if(this.camera.enabled)
    3. readInput = false;
    4.  
    Attach the following code to a camera object and don't forget a mouse look script. You can also code one into this script yourself.
    Code (csharp):
    1.  
    2. //flyspeed is multiplied by the current Axis value, ranging from 0 to 1, thus guaranteeing a smooth transition
    3. ///////between being stationary and moving.
    4.  
    5. //
    6. //NB!!! This script does not include mouse input. To be able to look around with your mouse, add the Mouse Look script from Unity's default camera control scripts!
    7. //
    8.  
    9. //The E and Q buttons can be used to move up and down with more ease.
    10. ///////The movement is done relative to your current rotation.
    11.  
    12. //This script is built so that it would be very easy to mess around with and improve or change - have a go!
    13. //For using Debug.Log, a function has already been created for you. This should keep things more tidied up.
    14. //Note: Debug text is not shown outside Unity's editor, thus not appearing in a standalone build
    15.  
    16. //You can toggle between defaultCam and Fly Cam with the default key, F12. The switching is done in the switchCamera function.
    17.  
    18. /*
    19. ////Feel free to use this code for whatever project you might need it for.
    20. ////Crediting me is not required.
    21. ////Have fun and good luck with your games!
    22. */
    23.  
    24. var flySpeed = 10;
    25. var defaultCam : GameObject;
    26. var playerObject : GameObject;
    27. var isEnabled : boolean;
    28.  
    29. var shift : boolean;
    30. var ctrl : boolean;
    31. var accelerationAmount : float = 30;
    32. var accelerationRatio : float = 3;
    33. var slowDownRatio : float = 0.2;
    34.  
    35.  
    36. function Update()
    37. {
    38.     //use shift to speed up flight
    39.     if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
    40.     {
    41.         shift = true;
    42.         flySpeed *= accelerationRatio;
    43.     }
    44.    
    45.     if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
    46.     {
    47.         shift = false;
    48.         flySpeed /= accelerationRatio;
    49.     }
    50.    
    51.     //use ctrl to slow up flight
    52.     if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
    53.     {
    54.         ctrl = true;
    55.         flySpeed *= slowDownRatio;
    56.     }
    57.    
    58.     if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.RightControl))
    59.     {
    60.         ctrl = false;
    61.         flySpeed /= slowDownRatio;
    62.     }
    63.     //
    64.     if (Input.GetAxis("Vertical") != 0)
    65.     {
    66.         transform.Translate(Vector3.forward * flySpeed * Input.GetAxis("Vertical"));
    67.     }
    68.    
    69.    
    70.     if (Input.GetAxis("Horizontal") != 0)
    71.     {
    72.         transform.Translate(Vector3.right * flySpeed * Input.GetAxis("Horizontal"));
    73.     }
    74.    
    75.    
    76.     if (Input.GetKey(KeyCode.E))
    77.     {
    78.         transform.Translate(Vector3.up * flySpeed);
    79.     }
    80.     else if (Input.GetKey(KeyCode.Q))
    81.     {
    82.         transform.Translate(Vector3.down * flySpeed);
    83.     }
    84.     if (Input.GetKeyDown(KeyCode.F12))
    85.         switchCamera();
    86.        
    87.     if (Input.GetKeyDown(KeyCode.M))
    88.         playerObject.transform.position = transform.position; //Moves the player to the flycam's position. Make sure not to just move the player's camera.
    89.        
    90.    
    91. }
    92. function switchCamera()
    93. {
    94.     if (!isEnabled) //means it is currently disabled. code will enable the flycam. you can NOT use 'enabled' as boolean's name.
    95.     {
    96.         transform.position = defaultCam.transform.position; //moves the flycam to the defaultcam's position
    97.         defaultCam.camera.active = false;
    98.         this.camera.active = true;
    99.         isEnabled = true;
    100.     }
    101.     else if (isEnabled) //if it is not disabled, it must be enabled. the function will disable the freefly camera this time.
    102.     {
    103.         this.camera.active = false;
    104.         defaultCam.camera.active = true;
    105.         isEnabled = false;
    106.     }
    107. }
    108.  
    I hope this helps you make awesomeness come to life with even more ease ;)
    Crediting me is of course not neccessary but a thank you is always nice :D

    Cheers :cool:
     
    Last edited: Jan 25, 2013
    dlanfranconi and ev88 like this.
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,435
    Thanks, had some use for this just now :)

    Made couple small modifications:
    - Now it moves in direction of the camera (used with this mouselook: http://forum.unity3d.com/threads/73117-A-Free-Simple-Smooth-Mouselook )
    - flyspeed is float (even 1 was too fast..)

    Code (csharp):
    1. var flySpeed:float = 0.5;
    2. var defaultCam : GameObject;
    3. var playerObject : GameObject;
    4. var isEnabled : boolean;
    5. var shift : boolean;
    6. var ctrl : boolean;
    7. var accelerationAmount : float = 3;
    8. var accelerationRatio : float = 1;
    9. var slowDownRatio : float = 0.5;
    10. function Update()
    11. {
    12.     if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
    13.     {
    14.         shift = true;
    15.         flySpeed *= accelerationRatio;
    16.     }
    17.    
    18.     if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
    19.     {
    20.         shift = false;
    21.         flySpeed /= accelerationRatio;
    22.     }
    23.     if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
    24.     {
    25.         ctrl = true;
    26.         flySpeed *= slowDownRatio;
    27.     }
    28.     if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.RightControl))
    29.     {
    30.         ctrl = false;
    31.         flySpeed /= slowDownRatio;
    32.     }
    33.     if (Input.GetAxis("Vertical") != 0)
    34.     {
    35.         transform.Translate(-defaultCam.transform.forward * flySpeed * Input.GetAxis("Vertical"));
    36.     }
    37.     if (Input.GetAxis("Horizontal") != 0)
    38.     {
    39.         transform.Translate(-defaultCam.transform.right * flySpeed * Input.GetAxis("Horizontal"));
    40.     }
    41.     if (Input.GetKey(KeyCode.E))
    42.     {
    43.         transform.Translate(defaultCam.transform.up * flySpeed*0.5f);
    44.     }
    45.     else if (Input.GetKey(KeyCode.Q))
    46.     {
    47.         transform.Translate(-defaultCam.transform.up * flySpeed*0.5f);
    48.     }
    49.     if (Input.GetKeyDown(KeyCode.F12))
    50.         switchCamera();
    51.     if (Input.GetKeyDown(KeyCode.M))
    52.         playerObject.transform.position = transform.position; //Moves the player to the flycam's position. Make sure not to just move the player's camera.
    53. }
    54. function switchCamera()
    55. {
    56.     if (!isEnabled) //means it is currently disabled. code will enable the flycam. you can NOT use 'enabled' as boolean's name.
    57.     {
    58.         transform.position = defaultCam.transform.position; //moves the flycam to the defaultcam's position
    59.         defaultCam.camera.active = false;
    60.         this.camera.active = true;
    61.         isEnabled = true;
    62.     }
    63.     else if (isEnabled) //if it is not disabled, it must be enabled. the function will disable the freefly camera this time.
    64.     {
    65.         this.camera.active = false;
    66.         defaultCam.camera.active = true;
    67.         isEnabled = false;
    68.     }
    69. }
     
  3. ttercero

    ttercero

    Joined:
    Jan 28, 2014
    Posts:
    1
    Could you please tell me how what script I have to add to this script for setting a maximum coordinate for the camera, Im using it for architectural visualization and it works great but I dont want it to move under the floor or to high in the sky. Sorry I am a newby at scripting.
     
  4. exorakhilas

    exorakhilas

    Joined:
    Jan 30, 2013
    Posts:
    4
    Thanks for this guys. I actually used the shooter script but adjusted the camera angle so that the player is not seen, thus looking like a fly through/first-person view.
     
  5. Eagle-Sense

    Eagle-Sense

    Joined:
    May 15, 2014
    Posts:
    7
    Thanks for sharing.
     
  6. WingBro

    WingBro

    Joined:
    Apr 30, 2014
    Posts:
    2

    Just to note this is a JS script not a C# script. I had a problem pasting it as a C#.
     
    dlanfranconi likes this.
  7. ZhavShaw

    ZhavShaw

    Joined:
    Aug 12, 2013
    Posts:
    173
    Here is C#
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FreeMovement : MonoBehaviour
    5. {
    6.     public float flySpeed = 0.5f;
    7.     public GameObject defaultCam;
    8.     public GameObject playerObject;
    9.     private bool isEnabled;
    10.     private bool shift;
    11.     private bool ctrl;
    12.     public float accelerationAmount = 3f;
    13.     public float accelerationRatio = 1f;
    14.     public float slowDownRatio = 0.5f;
    15.  
    16.     void Update()
    17.     {
    18.         if(Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
    19.         {
    20.             shift = true;
    21.             flySpeed *= accelerationRatio;
    22.         }
    23.  
    24.         if(Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
    25.         {
    26.             shift = false;
    27.             flySpeed /= accelerationRatio;
    28.         }
    29.         if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
    30.         {
    31.             ctrl = true;
    32.             flySpeed *= slowDownRatio;
    33.         }
    34.         if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.RightControl))
    35.         {
    36.             ctrl = false;
    37.             flySpeed /= slowDownRatio;
    38.         }
    39.         if (Input.GetAxis("Vertical") != 0)
    40.         {
    41.             transform.Translate(-defaultCam.transform.forward * flySpeed * Input.GetAxis("Vertical"));
    42.         }
    43.         if (Input.GetAxis("Horizontal") != 0)
    44.         {
    45.             transform.Translate(-defaultCam.transform.right * flySpeed * Input.GetAxis("Horizontal"));
    46.         }
    47.         if (Input.GetKey(KeyCode.E))
    48.         {
    49.             transform.Translate(defaultCam.transform.up * flySpeed*0.5f);
    50.         }
    51.         else if (Input.GetKey(KeyCode.Q))
    52.         {
    53.             transform.Translate(-defaultCam.transform.up * flySpeed*0.5f);
    54.         }
    55.         if (Input.GetKeyDown(KeyCode.F12))
    56.             switchCamera();
    57.         if (Input.GetKeyDown(KeyCode.M))
    58.             playerObject.transform.position = transform.position; //Moves the player to the flycam's position. Make sure not to just move the player's camera.
    59.     }
    60.  
    61.     void switchCamera()
    62.     {
    63.         if (!isEnabled) //means it is currently disabled. code will enable the flycam. you can NOT use 'enabled' as boolean's name.
    64.         {
    65.             transform.position = defaultCam.transform.position; //moves the flycam to the defaultcam's position
    66.             defaultCam.GetComponent<Camera>().enabled = false;
    67.             this.GetComponent<Camera>().enabled = true;
    68.             isEnabled = true;
    69.         }
    70.         else if (isEnabled) //if it is not disabled, it must be enabled. the function will disable the freefly camera this time.
    71.         {
    72.             this.GetComponent<Camera>().enabled = false;
    73.             defaultCam.GetComponent<Camera>().enabled = true;
    74.             isEnabled = false;
    75.         }
    76.     }
    77. }
     
  8. Zyxil

    Zyxil

    Joined:
    Nov 23, 2009
    Posts:
    111
    Combined the mouselook from the other thread and cleaned up the movement bits. Toggled by LeftShift.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. // Very simple smooth mouselook modifier for the MainCamera in Unity
    4. // by Francis R. Griffiths-Keam - www.runningdimensions.com
    5. // http://forum.unity3d.com/threads/a-free-simple-smooth-mouselook.73117/
    6.  
    7.  
    8. public class MouseLook : MonoBehaviour
    9. {
    10.     Vector2 _mouseAbsolute;
    11.     Vector2 _smoothMouse;
    12.  
    13.     public Vector2 clampInDegrees = new Vector2(360, 180);
    14.     public Vector2 sensitivity = new Vector2(2, 2);
    15.     public Vector2 smoothing = new Vector2(3, 3);
    16.     public Vector2 targetDirection;
    17.     public Vector2 targetCharacterDirection;
    18.  
    19.     // Assign this if there's a parent object controlling motion, such as a Character Controller.
    20.     // Yaw rotation will affect this object instead of the camera if set.
    21.     public GameObject characterBody;
    22.  
    23.     private Background _background;
    24.     private bool _mouselookEnabled = false;
    25.     private bool _shifted = false;
    26.     public float flySpeed = 0.5f;
    27.     public GameObject defaultCamera;
    28.  
    29.  
    30.     void Start()
    31.     {
    32.         // Set target direction to the camera's initial orientation.
    33.         targetDirection = transform.localRotation.eulerAngles;
    34.  
    35.         // Set target direction for the character body to its inital state.
    36.         if (characterBody)
    37.             targetCharacterDirection = characterBody.transform.localRotation.eulerAngles;
    38.  
    39.         _background = GameObject.FindGameObjectWithTag("Background").GetComponent<Background>();
    40.     }
    41.  
    42.     void Update()
    43.     {
    44.         if (_background.InLobby)
    45.             return;
    46.  
    47.         if (Input.GetKeyUp(KeyCode.LeftShift) & _shifted)
    48.             _shifted = false;
    49.  
    50.         if ((Input.GetKeyDown(KeyCode.LeftShift) & !_shifted) |
    51.             (Input.GetKeyDown(KeyCode.Escape) & _mouselookEnabled))
    52.         {
    53.             _shifted = true;
    54.  
    55.             if (!_mouselookEnabled)
    56.             {
    57.                 _mouselookEnabled = true;
    58.                 Cursor.lockState = CursorLockMode.Locked;
    59.                 Cursor.visible = false;
    60.             }
    61.             else
    62.             {
    63.                 if (Input.GetKeyDown(KeyCode.Escape))
    64.                     _shifted = false;
    65.                    
    66.                 _mouselookEnabled = false;
    67.                 Cursor.lockState = CursorLockMode.None;
    68.                 Cursor.visible = true;
    69.             }
    70.         }
    71.  
    72.         if (!_mouselookEnabled)
    73.             return;
    74.  
    75.         //ensure these stay this way
    76.         Cursor.lockState = CursorLockMode.Locked;
    77.         Cursor.visible = false;
    78.  
    79.         // Allow the script to clamp based on a desired target value.
    80.         var targetOrientation = Quaternion.Euler(targetDirection);
    81.         var targetCharacterOrientation = Quaternion.Euler(targetCharacterDirection);
    82.  
    83.         // Get raw mouse input for a cleaner reading on more sensitive mice.
    84.         var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    85.  
    86.         // Scale input against the sensitivity setting and multiply that against the smoothing value.
    87.         mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y));
    88.  
    89.         // Interpolate mouse movement over time to apply smoothing delta.
    90.         _smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x);
    91.         _smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y);
    92.  
    93.         // Find the absolute mouse movement value from point zero.
    94.         _mouseAbsolute += _smoothMouse;
    95.  
    96.         // Clamp and apply the local x value first, so as not to be affected by world transforms.
    97.         if (clampInDegrees.x < 360)
    98.             _mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f);
    99.  
    100.         // Then clamp and apply the global y value.
    101.         if (clampInDegrees.y < 360)
    102.             _mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f);
    103.  
    104.         var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right);
    105.         transform.localRotation = xRotation * targetOrientation;
    106.  
    107.         // If there's a character body that acts as a parent to the camera
    108.         if (characterBody)
    109.         {
    110.             var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, characterBody.transform.up);
    111.             characterBody.transform.localRotation = yRotation;
    112.             characterBody.transform.localRotation *= targetCharacterOrientation;
    113.         }
    114.         else
    115.         {
    116.             var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, transform.InverseTransformDirection(Vector3.up));
    117.             transform.localRotation *= yRotation;
    118.         }
    119.  
    120.         //movement
    121.         if (Input.GetAxis("Vertical") != 0)
    122.         {
    123.             transform.Translate(defaultCamera.transform.forward * flySpeed * Input.GetAxis("Vertical"), Space.World);
    124.         }
    125.         if (Input.GetAxis("Horizontal") != 0)
    126.         {
    127.             transform.Translate(defaultCamera.transform.right * flySpeed * Input.GetAxis("Horizontal"), Space.World);
    128.         }
    129.         if (Input.GetKey(KeyCode.R))
    130.         {
    131.             transform.Translate(Vector3.up * flySpeed * 0.5f, Space.World);
    132.         }
    133.         else if (Input.GetKey(KeyCode.W))
    134.         {
    135.             transform.Translate(-Vector3.up * flySpeed * 0.5f, Space.World);
    136.         }
    137.     }
    138. }
     
    eobet likes this.
  9. Lagger625

    Lagger625

    Joined:
    Mar 7, 2016
    Posts:
    10
    I made a very simple and fully-functional flycam script. Attach this CameraController.cs to the camera. Look around with mouse, move with WASD, go up and down with E and Q, rotate with R and F. Increase and decrease movement speed at your full desire with mouse wheel! Don't forget to configure the Depth and Rotation axes in Edit > Project Settings > Input by duplicating Horizontal or Vertical axes and configuring the negative and positive buttons to E, Q, R and F or anything else.
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CameraController : MonoBehaviour {
    4.  
    5.     private static float movementSpeed = 1.0f;
    6.  
    7.     void Update () {
    8.         movementSpeed = Mathf.Max(movementSpeed += Input.GetAxis("Mouse ScrollWheel"), 0.0f);
    9.         transform.position += (transform.right * Input.GetAxis("Horizontal") + transform.forward * Input.GetAxis("Vertical") + transform.up * Input.GetAxis("Depth")) * movementSpeed;
    10.         transform.eulerAngles += new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), Input.GetAxis("Rotation"));
    11.     }
    12. }
    13.  
     
  10. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    Thank you for sharing.
    I wish to see new part of unity forum where you can find free scripts or tutorials. Yes, this will not encourage people to search and learn to read codes. But is good and healthful.
    Thank you guys.
     
  11. Anutrix

    Anutrix

    Joined:
    Dec 17, 2017
    Posts:
    4
    Can someone tell me what to set for GetAxis("Depth") in @Lagger625's code?
     
  12. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,435
    At the end of his message,
     
  13. Keepps65

    Keepps65

    Joined:
    Oct 26, 2017
    Posts:
    4
    Thanks, very useful.
     
  14. JakubNei

    JakubNei

    Joined:
    Jul 20, 2013
    Posts:
    26
    Here is my custom simple verson, behaves almost the same as Editor Scene view camera

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine;
    3.  
    4. [RequireComponent(typeof(Camera))]
    5. public class MouseLook : MonoBehaviour
    6. {
    7.     public Vector2 mouseAbsolute;
    8.     public Vector2 mouseClampInDegrees = new Vector2(360, 180);
    9.     public Vector2 mouseSensitivity = new Vector2(500, 500);
    10.     public float moveSpeed = 20.0f;
    11.  
    12.     void Update()
    13.     {
    14.         if (!Input.GetKey(KeyCode.Mouse1))
    15.             return;
    16.  
    17.         var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    18.         var moveDelta = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    19.         if (Input.GetKey(KeyCode.Q))
    20.             moveDelta.y += 1;
    21.         if (Input.GetKey(KeyCode.E))
    22.             moveDelta.y -= 1;
    23.         var speedBoost = Input.GetKey(KeyCode.LeftShift);
    24.         var moveSpeedAdjust = Input.GetAxis("Mouse ScrollWheel");
    25.  
    26.         mouseDelta = Vector2.Scale(mouseDelta, mouseSensitivity);
    27.         mouseDelta *= Time.deltaTime;
    28.         moveSpeed = Mathf.Pow(moveSpeed, 1 + moveSpeedAdjust * Time.deltaTime * 30);
    29.         moveDelta *= moveSpeed;
    30.         if (speedBoost)
    31.             moveDelta *= 4;
    32.         moveDelta *= Time.deltaTime;
    33.         mouseAbsolute += mouseDelta;
    34.         if (mouseClampInDegrees.x <= 360)
    35.             mouseAbsolute.x = Mathf.Clamp(mouseAbsolute.x, -mouseClampInDegrees.x * 0.5f, mouseClampInDegrees.x * 0.5f);
    36.         if (mouseClampInDegrees.y <= 360)
    37.             mouseAbsolute.y = Mathf.Clamp(mouseAbsolute.y, -mouseClampInDegrees.y * 0.5f, mouseClampInDegrees.y * 0.5f);
    38.  
    39.         transform.rotation = Quaternion.AngleAxis(mouseAbsolute.x, Vector3.up) * Quaternion.AngleAxis(-mouseAbsolute.y, Vector3.right);
    40.         transform.position = transform.position + transform.rotation * moveDelta;
    41.     }
    42. }
    43. }
     
    Last edited: Feb 17, 2023