Search Unity

  1. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  2. Want more efficiency in your development work? Sign up to receive weekly tech and creative know-how from Unity experts.
    Dismiss Notice
  3. Participate with students all over the world and build projects to teach people. Join now!
    Dismiss Notice
  4. Build games and experiences that can load instantly and without install. Explore the Project Tiny Preview today!
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  6. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Fly Cam (simple cam script)

Discussion in 'Made With Unity' started by windexglow, Nov 13, 2010.

  1. windexglow

    windexglow

    Joined:
    Jun 18, 2010
    Posts:
    378
    I've been needing a fly script but couldn't find one. So I made one. Should work as a plugnplay, and easy to customize. No credit required.
    EDIT: by 'fly cam' I mean a camera that flies around. Not an insect fly.
    Code (csharp):
    1. /*
    2. Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.  
    3. Simple flycam I made, since I couldn't find any others made public.  
    4. Made simple to use (drag and drop, done) for regular keyboard layout  
    5. wasd : basic movement
    6. shift : Makes camera accelerate
    7. space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/
    8.  
    9.  
    10. var mainSpeed : float = 100.0; //regular speed
    11. var shiftAdd : float = 250.0; //multiplied by how long shift is held.  Basically running
    12. var maxShift : float = 1000.0; //Maximum speed when holdin gshift
    13. var camSens : float = 0.25; //How sensitive it with mouse
    14. private var lastMouse = Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
    15. private var totalRun : float  = 1.0;
    16.  
    17. function Update () {
    18.     lastMouse = Input.mousePosition - lastMouse ;
    19.     lastMouse = Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 );
    20.     lastMouse = Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0);
    21.     transform.eulerAngles = lastMouse;
    22.     lastMouse =  Input.mousePosition;
    23.     //Mouse  camera angle done.  
    24.    
    25.     //Keyboard commands
    26.     var f : float = 0.0;
    27.     var p = GetBaseInput();
    28.     if (Input.GetKey (KeyCode.LeftShift)){
    29.         totalRun += Time.deltaTime;
    30.         p  = p * totalRun * shiftAdd;
    31.         p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    32.         p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    33.         p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    34.     }
    35.     else{
    36.         totalRun = Mathf.Clamp(totalRun * 0.5, 1, 1000);
    37.         p = p * mainSpeed;
    38.     }
    39.    
    40.     p = p * Time.deltaTime;
    41.     if (Input.GetKey(KeyCode.Space)){ //If player wants to move on X and Z axis only
    42.         f = transform.position.y;
    43.         transform.Translate(p);
    44.         transform.position.y = f;
    45.     }
    46.     else{
    47.         transform.Translate( p);
    48.     }
    49.    
    50. }
    51.  
    52. private function GetBaseInput() : Vector3 { //returns the basic values, if it's 0 than it's not active.
    53.     var p_Velocity : Vector3;
    54.     if (Input.GetKey (KeyCode.W)){
    55.         p_Velocity += Vector3(0, 0 , 1);
    56.     }
    57.     if (Input.GetKey (KeyCode.S)){
    58.         p_Velocity += Vector3(0, 0 , -1);
    59.     }
    60.     if (Input.GetKey (KeyCode.A)){
    61.         p_Velocity += Vector3(-1, 0 , 0);
    62.     }
    63.     if (Input.GetKey (KeyCode.D)){
    64.         p_Velocity += Vector3(1, 0 , 0);
    65.     }
    66.     return p_Velocity;
    67. }
     
  2. briosh

    briosh

    Joined:
    Aug 9, 2010
    Posts:
    17
    thanks, i love finding scripts like that, especialy when i need them for a quick test -not the actual project- and dodge the hours of coding :)
     
  3. softwizz

    softwizz

    Joined:
    Mar 12, 2011
    Posts:
    794
    artofmining likes this.
  4. fromfame

    fromfame

    Joined:
    Jul 21, 2012
    Posts:
    17
    Thanks loads! that surely was needed!
     
  5. Ellandar

    Ellandar

    Joined:
    Jan 5, 2013
    Posts:
    207
    Hi All,

    Was just looking for Unityscript to practice converting to C# so trawled the forum for candidates.
    Hope it saves someone some time.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FlyCamera : MonoBehaviour {
    5.  
    6.     /*
    7.     Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.  
    8.     Converted to C# 27-02-13 - no credit wanted.
    9.     Simple flycam I made, since I couldn't find any others made public.  
    10.     Made simple to use (drag and drop, done) for regular keyboard layout  
    11.     wasd : basic movement
    12.     shift : Makes camera accelerate
    13.     space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/
    14.      
    15.      
    16.     float mainSpeed = 100.0f; //regular speed
    17.     float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
    18.     float maxShift = 1000.0f; //Maximum speed when holdin gshift
    19.     float camSens = 0.25f; //How sensitive it with mouse
    20.     private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
    21.     private float totalRun= 1.0f;
    22.      
    23.     void Update () {
    24.         lastMouse = Input.mousePosition - lastMouse ;
    25.         lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 );
    26.         lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0);
    27.         transform.eulerAngles = lastMouse;
    28.         lastMouse =  Input.mousePosition;
    29.         //Mouse  camera angle done.  
    30.        
    31.         //Keyboard commands
    32.         float f = 0.0f;
    33.         Vector3 p = GetBaseInput();
    34.         if (Input.GetKey (KeyCode.LeftShift)){
    35.             totalRun += Time.deltaTime;
    36.             p  = p * totalRun * shiftAdd;
    37.             p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    38.             p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    39.             p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    40.         }
    41.         else{
    42.             totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
    43.             p = p * mainSpeed;
    44.         }
    45.        
    46.         p = p * Time.deltaTime;
    47.        Vector3 newPosition = transform.position;
    48.         if (Input.GetKey(KeyCode.Space)){ //If player wants to move on X and Z axis only
    49.             transform.Translate(p);
    50.             newPosition.x = transform.position.x;
    51.             newPosition.z = transform.position.z;
    52.             transform.position = newPosition;
    53.         }
    54.         else{
    55.             transform.Translate(p);
    56.         }
    57.        
    58.     }
    59.      
    60.     private Vector3 GetBaseInput() { //returns the basic values, if it's 0 than it's not active.
    61.         Vector3 p_Velocity = new Vector3();
    62.         if (Input.GetKey (KeyCode.W)){
    63.             p_Velocity += new Vector3(0, 0 , 1);
    64.         }
    65.         if (Input.GetKey (KeyCode.S)){
    66.             p_Velocity += new Vector3(0, 0, -1);
    67.         }
    68.         if (Input.GetKey (KeyCode.A)){
    69.             p_Velocity += new Vector3(-1, 0, 0);
    70.         }
    71.         if (Input.GetKey (KeyCode.D)){
    72.             p_Velocity += new Vector3(1, 0, 0);
    73.         }
    74.         return p_Velocity;
    75.     }
    76. }
     
    Last edited: Feb 28, 2013
  6. mattBarker

    mattBarker

    Joined:
    Oct 9, 2012
    Posts:
    6
    thanks a lot, i've been missing this functionality
     
  7. RoiDanton

    RoiDanton

    Joined:
    Apr 14, 2014
    Posts:
    4
    Thanks for the script and the conversion! Small additions (resetRotation(), RF strafe control, improved initial mouse position):
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FlyCamera : MonoBehaviour {
    5.  
    6.     /**
    7.      * Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.
    8.      * Converted to C# 27-02-13 - no credit wanted.
    9.      * Added resetRotation, RF control, improved initial mouse position, 2015-03-11 - Roi Danton.
    10.      * Simple flycam I made, since I couldn't find any others made public.
    11.      * Made simple to use (drag and drop, done) for regular keyboard layout
    12.      * wasdrf : basic movement
    13.      * shift : Makes camera accelerate
    14.      * space : Moves camera on X and Z axis only.  So camera doesn't gain any height
    15.      */
    16.  
    17.     float mainSpeed = 10f; // Regular speed.
    18.     float shiftAdd = 25f;  // Multiplied by how long shift is held.  Basically running.
    19.     float maxShift = 100f; // Maximum speed when holding shift.
    20.     float camSens = .35f;  // Camera sensitivity by mouse input.
    21.     private Vector3 lastMouse = new Vector3(Screen.width/2, Screen.height/2, 0); // Kind of in the middle of the screen, rather than at the top (play).
    22.     private float totalRun= 1.0f;
    23.  
    24.     void Update () {
    25.  
    26.         // Mouse input.
    27.         lastMouse = Input.mousePosition - lastMouse;
    28.         lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 );
    29.         lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0);
    30.         transform.eulerAngles = lastMouse;
    31.         lastMouse =  Input.mousePosition;
    32.  
    33.         // Keyboard commands.
    34.         Vector3 p = getDirection();
    35.         if (Input.GetKey (KeyCode.LeftShift)){
    36.             totalRun += Time.deltaTime;
    37.             p  = p * totalRun * shiftAdd;
    38.             p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    39.             p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    40.             p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    41.         }
    42.         else{
    43.             totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
    44.             p = p * mainSpeed;
    45.         }
    46.      
    47.         p = p * Time.deltaTime;
    48.         Vector3 newPosition = transform.position;
    49.         if (Input.GetKey(KeyCode.V)){ //If player wants to move on X and Z axis only
    50.             transform.Translate(p);
    51.             newPosition.x = transform.position.x;
    52.             newPosition.z = transform.position.z;
    53.             transform.position = newPosition;
    54.         }
    55.         else{
    56.             transform.Translate(p);
    57.         }
    58.      
    59.     }
    60.  
    61.     private Vector3 getDirection() {
    62.         Vector3 p_Velocity = new Vector3();
    63.         if (Input.GetKey (KeyCode.W)){
    64.             p_Velocity += new Vector3(0, 0 , 1);
    65.         }
    66.         if (Input.GetKey (KeyCode.S)){
    67.             p_Velocity += new Vector3(0, 0, -1);
    68.         }
    69.         if (Input.GetKey (KeyCode.A)){
    70.             p_Velocity += new Vector3(-1, 0, 0);
    71.         }
    72.         if (Input.GetKey (KeyCode.D)){
    73.             p_Velocity += new Vector3(1, 0, 0);
    74.         }
    75.         if (Input.GetKey (KeyCode.R)){
    76.             p_Velocity += new Vector3(0, 1, 0);
    77.         }
    78.         if (Input.GetKey (KeyCode.F)){
    79.             p_Velocity += new Vector3(0, -1, 0);
    80.         }
    81.         return p_Velocity;
    82.     }
    83.  
    84.     public void resetRotation(Vector3 lookAt) {
    85.         transform.LookAt(lookAt);
    86.     }
    87. }
    88.  
     
    Last edited: Mar 11, 2015
  8. Teadaddy

    Teadaddy

    Joined:
    Jan 26, 2015
    Posts:
    22
    Script is great, I have used it to base a camera I am building and I wonder if anyone might have a perspective on how to do the following-
    I have a series of targets to .LookAt given various UI or keyboard inputs. I want to set the camera to rotate the object looked at i.e Target Camera. However, when I move away from the target through WASD or LMB, I want the camera axis to return to the camera.

    Any idears?
    Many Thanks!
     
  9. agilelensalex

    agilelensalex

    Joined:
    Apr 7, 2014
    Posts:
    22
    hey folks-- I love this script and have been using it a lot. One thing I'm trying to implement is 'tilt', like when a plane does a barrel roll. I know the hang up is in the 'lastMouse' variable which constantly resets to 0, but I'm finding that even if I try to give it a value, it still resets to zero! Any thoughts? Thanks!
     
  10. alcamedes

    alcamedes

    Joined:
    Mar 26, 2014
    Posts:
    5
    This has saved me so much headache. Thanks to the authors!
     
  11. LookForward

    LookForward

    Joined:
    Sep 25, 2015
    Posts:
    2
    Hey. I little improve that script.
    Add "walker" mode and remade rotating.
    But it needs Character Controller.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FlyCamera : MonoBehaviour {
    5.  
    6.     /**
    7.      * Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.
    8.      * Converted to C# 27-02-13 - no credit wanted.
    9.      * Added resetRotation, RF control, improved initial mouse position, 2015-03-11 - Roi Danton.
    10.      * Remaded camera rotation - now cursor is locked, added "Walker Mode", 25-09-15 - LookForward.
    11.      * Simple flycam I made, since I couldn't find any others made public.
    12.      * Made simple to use (drag and drop, done) for regular keyboard layout
    13.      * wasdrf : Basic movement
    14.      * shift : Makes camera accelerate
    15.      * space : Moves camera on X and Z axis only.  So camera doesn't gain any height
    16.      * q : Change mode
    17.      */
    18.  
    19.     public float mouseSensitivity     = 5.0f;        // Mouse rotation sensitivity.
    20.     public float speed                = 10.0f;    // Regular speed.
    21.     public float gravity            = 20.0f;    // Gravity force.
    22.     public float shiftAdd            = 25.0f;    // Multiplied by how long shift is held.  Basically running.
    23.     public float maxShift            = 100.0f;    // Maximum speed when holding shift.
    24.     public bool  walkerMode         = false;    // Walker Mode.
    25.  
    26.     private float totalRun            = 1.0f;
    27.     private float rotationY            = 0.0f;
    28.     private float maximumY            = 90.0f;    // Not recommended to change
    29.     private float minimumY            = -90.0f;    // these parameters.
    30.     private CharacterController controller;
    31.  
    32.     void Start() {
    33.         controller = GetComponent<CharacterController>();
    34.         Cursor.lockState = CursorLockMode.Locked;
    35.     }
    36.  
    37.     void Update() {
    38.         if (Input.GetKeyUp(KeyCode.Q)) {
    39.             // Toggle mode.
    40.             walkerMode = !walkerMode;
    41.         }
    42.     }
    43.  
    44.     void FixedUpdate () {
    45.         // Mouse commands.
    46.         float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mouseSensitivity;          
    47.         rotationY += Input.GetAxis("Mouse Y") * mouseSensitivity;
    48.         rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);          
    49.         transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0.0f);
    50.      
    51.         // Keyboard commands.
    52.         Vector3 p = getDirection();
    53.         if (Input.GetKey(KeyCode.LeftShift)) {
    54.             totalRun += Time.deltaTime;
    55.             p  = p * totalRun * shiftAdd;
    56.             p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    57.             p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    58.             p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    59.         } else {
    60.             totalRun = Mathf.Clamp(totalRun * 0.5f, 1.0f, 1000.0f);
    61.             p = p * speed;
    62.         }
    63.      
    64.         p = p * Time.deltaTime;
    65.         Vector3 newPosition = transform.position;
    66.         if (walkerMode) {
    67.             // Walker Mode.
    68.             p = transform.TransformDirection(p);
    69.             p.y = 0.0f;
    70.             p.y -= gravity * Time.deltaTime;
    71.             controller.Move(p);
    72.         } else {
    73.             // Fly Mode.
    74.             if (Input.GetButton("Jump")) { // If player wants to move on X and Z axis only (sliding)
    75.                 transform.Translate(p);
    76.                 newPosition.x = transform.position.x;
    77.                 newPosition.z = transform.position.z;
    78.                 transform.position = newPosition;
    79.             } else {
    80.                 transform.Translate(p);
    81.             }
    82.         }
    83.     }
    84.  
    85.     private Vector3 getDirection() {
    86.         Vector3 p_Velocity = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
    87.         // Strifing enabled only in Fly Mode.
    88.         if (!walkerMode) {
    89.             if (Input.GetKey(KeyCode.F)) {
    90.                 p_Velocity += new Vector3(0.0f, -1.0f, 0.0f);
    91.             }
    92.             if (Input.GetKey(KeyCode.R)) {
    93.                 p_Velocity += new Vector3(0.0f, 1.0f, 0.0f);
    94.             }
    95.         }
    96.         return p_Velocity;
    97.     }
    98.  
    99.     public void resetRotation(Vector3 lookAt) {
    100.         transform.LookAt(lookAt);
    101.     }
    102. }
     
    Last edited: Oct 4, 2015
    Paul_from_Australia and SAOTA like this.
  12. IndieAner3d

    IndieAner3d

    Joined:
    Oct 20, 2014
    Posts:
    77
    Hii@LookForward
    "Add ground mode"
    Do you mean ground Vehicle with that...!?!
     
  13. LookForward

    LookForward

    Joined:
    Sep 25, 2015
    Posts:
    2
    I mean walker mode, like a simple man. But english isn't my native language - and so I could make a mistake. I'll be glad, if you correct me. =)
     
    IndieAner3d likes this.
  14. neduser

    neduser

    Joined:
    Jul 30, 2012
    Posts:
    5
    Big thanks for this script.
     
  15. Pattywagon

    Pattywagon

    Joined:
    Jan 5, 2016
    Posts:
    1
    This is obviously fake I tested don't use this it is a waste of time
     
  16. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,142
    @Pattywagon just tested LookForward's (i.e. latest) version myself and it's working fine. There is an unhandled exception when attempting to use "walker mode" without a charactercontroller attached to the gameobject, but other than that it's working fine. The prior versions suffer from the lack of cursor lock though :confused:

    @LookForward don't forget there is a "require component" functionality which really helps when you are putting out code to the big world with dependencies.
    http://docs.unity3d.com/ScriptReference/RequireComponent.html
    Or include checks for missing components before attempting to use them :)
     
    Paul_from_Australia likes this.
  17. Paul_from_Australia

    Paul_from_Australia

    Joined:
    Jan 26, 2016
    Posts:
    1
    Thanks, very helpful script!
     
  18. artofmining

    artofmining

    Joined:
    May 1, 2016
    Posts:
    18
    Great handy script for a Unity newbie like me .. I wonder if one of you brainiac geniuses could make a 360 continuous rotate option for it? And a basic UP/DOWN (raise lower)
    I have a long term plan for some VR environments using HTC and would like to implement a DRONE like operation where the object does a fly thro but could do full continuous rotation when stationary or moving. ON the drone controller the sticks self centre so holding hard left keeps the drone rotating. As this script uses mouse, if you maintain tight turns or use a joystick it cause runoff due to reading mouse XY. Think of being able to hover and continuously rotate around the scene. IF anyone could point me to the code suggestion I'd be very grateful and I'm sure it be useful for others too. I see the basic code but not savvy to how you could implement rotation. And the UP/DOWN features. ANY HELP REALLY APPRECIATED ! Thanks Archie
     
  19. Angryboy

    Angryboy

    Joined:
    Apr 9, 2014
    Posts:
    2
    Currently working on a modified version in C# that includes hold-to-rotate and an up/down feature, if that's of any use?
    Unfortunately I don't quite understand what you mean by rotation, perhaps you could clarify?
     
  20. Angryboy

    Angryboy

    Joined:
    Apr 9, 2014
    Posts:
    2
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class camera_movement : MonoBehaviour {
    5.  
    6.     /*
    7.      * Based on Windex's flycam script found here: http://forum.unity3d.com/threads/fly-cam-simple-cam-script.67042/
    8.      * C# conversion created by Ellandar
    9.      * Improved camera made by LookForward
    10.      * Modifications created by Angryboy
    11.      * 1) Have to hold right-click to rotate
    12.      * 2) Made variables public for testing/designer purposes
    13.      * 3) Y-axis now locked (as if space was always being held)
    14.      * 4) Q/E keys are used to raise/lower the camera
    15.      */
    16.  
    17.     public float mainSpeed = 100.0f; //regular speed
    18.     public float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
    19.     public float maxShift = 1000.0f; //Maximum speed when holdin gshift
    20.     public float camSens = 0.25f; //How sensitive it with mouse
    21.     private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
    22.     private float totalRun= 1.0f;
    23.  
    24.     private bool isRotating = false; // Angryboy: Can be called by other things (e.g. UI) to see if camera is rotating
    25.     private float speedMultiplier; // Angryboy: Used by Y axis to match the velocity on X/Z axis
    26.  
    27.     public float mouseSensitivity     = 5.0f;        // Mouse rotation sensitivity.
    28.     private float rotationY            = 0.0f;
    29.  
    30.    
    31.     void Update () {
    32.  
    33.         // Angryboy: Hold right-mouse button to rotate
    34.         if (Input.GetMouseButtonDown (1)) {
    35.             isRotating = true;
    36.         }
    37.         if (Input.GetMouseButtonUp (1)) {
    38.             isRotating = false;
    39.         }
    40.         if (isRotating) {
    41.             // Made by LookForward
    42.             // Angryboy: Replaced min/max Y with numbers, not sure why we had variables in the first place
    43.             float rotationX = transform.localEulerAngles.y + Input.GetAxis ("Mouse X") * mouseSensitivity;        
    44.             rotationY += Input.GetAxis ("Mouse Y") * mouseSensitivity;
    45.             rotationY = Mathf.Clamp (rotationY, -90, 90);        
    46.             transform.localEulerAngles = new Vector3 (-rotationY, rotationX, 0.0f);
    47.         }
    48.        
    49.         //Keyboard commands
    50.         float f = 0.0f;
    51.         Vector3 p = GetBaseInput();
    52.         if (Input.GetKey (KeyCode.LeftShift)){
    53.             totalRun += Time.deltaTime;
    54.             p  = p * totalRun * shiftAdd;
    55.             p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    56.             p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    57.             p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    58.             // Angryboy: Use these to ensure that Y-plane is affected by the shift key as well
    59.             speedMultiplier = totalRun * shiftAdd * Time.deltaTime;
    60.             speedMultiplier = Mathf.Clamp(speedMultiplier, -maxShift, maxShift);
    61.         }
    62.         else{
    63.             totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
    64.             p = p * mainSpeed;
    65.             speedMultiplier = mainSpeed * Time.deltaTime; // Angryboy: More "correct" speed
    66.         }
    67.        
    68.         p = p * Time.deltaTime;
    69.  
    70.         // Angryboy: Removed key-press requirement, now perma-locked to the Y plane
    71.         Vector3 newPosition = transform.position;//If player wants to move on X and Z axis only
    72.         transform.Translate(p);
    73.         newPosition.x = transform.position.x;
    74.         newPosition.z = transform.position.z;
    75.  
    76.         // Angryboy: Manipulate Y plane by using Q/E keys
    77.         if (Input.GetKey (KeyCode.Q)){
    78.             newPosition.y += -speedMultiplier;
    79.         }
    80.         if (Input.GetKey (KeyCode.E)){
    81.             newPosition.y += speedMultiplier;
    82.         }
    83.  
    84.         transform.position = newPosition;
    85.     }
    86.  
    87.     // Angryboy: Can be called by other code to see if camera is rotating
    88.     // Might be useful in UI to stop accidental clicks while turning?
    89.     public bool amIRotating(){
    90.         return isRotating;
    91.     }
    92.    
    93.     private Vector3 GetBaseInput() { //returns the basic values, if it's 0 than it's not active.
    94.         Vector3 p_Velocity = new Vector3();
    95.         if (Input.GetKey (KeyCode.W)){
    96.             p_Velocity += new Vector3(0, 0 , 1);
    97.         }
    98.         if (Input.GetKey (KeyCode.S)){
    99.             p_Velocity += new Vector3(0, 0, -1);
    100.         }
    101.         if (Input.GetKey (KeyCode.A)){
    102.             p_Velocity += new Vector3(-1, 0, 0);
    103.         }
    104.         if (Input.GetKey (KeyCode.D)){
    105.             p_Velocity += new Vector3(1, 0, 0);
    106.         }
    107.         return p_Velocity;
    108.     }
    109. }
    110.  
    For those interested in a slightly modified version I worked on.
    Doesn't require space to lock to the Y plane, uses Q/E buttons to raise and lower instead.
    Also using LockForward's improved camera rotation as well as a button requirement to move it.
    I suppose this version works better for RTS style cameras? Enjoy!
     
  21. artofmining

    artofmining

    Joined:
    May 1, 2016
    Posts:
    18
    Oh Hi sorry I've not been on here in a while .. busy with end of year art work. Thanks again for this. I found one issue when I went to compile as an exe it failed .. I haven't looked at it since but I remember that issue
     
  22. artofmining

    artofmining

    Joined:
    May 1, 2016
    Posts:
    18
    The rotation thing I meant is .. continuous revolutions in one spot 360 endless .. pitch roll and yaw it might be known as.
    So the drone would hover and you can pan 360 or more in an endless loop as long as key pressed .. just spin basically .. and keep spinning if you hold the button.

    Thanks for taking the time on this appreciated !!
     
  23. umer-azeem

    umer-azeem

    Joined:
    Dec 13, 2015
    Posts:
    2
    Works like a charm. Thanks
     
  24. visioneers

    visioneers

    Joined:
    Aug 26, 2016
    Posts:
    1
    Thanks for this!
     
  25. lindaz

    lindaz

    Joined:
    Apr 14, 2017
    Posts:
    1
    Thank you so much!! It works like a charm :)
     
  26. EyePD

    EyePD

    Joined:
    Feb 26, 2016
    Posts:
    31
    Good job & thanks for making this, I really wish Unity would simply just include this with the Standard Assets package!
     
  27. micah_3d

    micah_3d

    Joined:
    Jan 7, 2015
    Posts:
    4
    Camera works perfectly! Thanks to all who have contributed and a special thanks to Windexglow for starting this thread.
     
  28. micah_3d

    micah_3d

    Joined:
    Jan 7, 2015
    Posts:
    4
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class FlyingCamera : MonoBehaviour {
    6.     /*
    7.      * Based on Windex's flycam script found here: http://forum.unity3d.com/threads/fly-cam-simple-cam-script.67042/
    8.      * C# conversion created by Ellandar
    9.      * Improved camera made by LookForward
    10.      * Modifications created by Angryboy
    11.      * 1) Have to hold right-click to rotate
    12.      * 2) Made variables public for testing/designer purposes
    13.      * 3) Y-axis now locked (as if space was always being held)
    14.      * 4) Q/E keys are used to raise/lower the camera
    15.      *
    16.      * Another Modification created by micah_3d
    17.      * 1) adding an isColliding bool to allow camera to collide with world objects, terrain etc.
    18.      */
    19.  
    20.     public float mainSpeed = 100.0f; //regular speed
    21.     public float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
    22.     public float maxShift = 1000.0f; //Maximum speed when holdin gshift
    23.     public float camSens = 0.25f; //How sensitive it with mouse
    24.     private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
    25.     private float totalRun= 1.0f;
    26.  
    27.     private bool isRotating = false; // Angryboy: Can be called by other things (e.g. UI) to see if camera is rotating
    28.     private float speedMultiplier; // Angryboy: Used by Y axis to match the velocity on X/Z axis
    29.  
    30.     public float mouseSensitivity     = 5.0f;        // Mouse rotation sensitivity.
    31.     private float rotationY            = 0.0f;
    32.  
    33.     //micah_3d: added so camera will be able to collide with world objects if users chooses
    34.     public bool isColliding = true;
    35.     //physic material added to keep camera from spinning out of control if it hits a corner or multiple colliders at the same time.  
    36.     PhysicMaterial myMaterial;
    37.  
    38.     void Start(){
    39.         if (isColliding == true) {
    40.             myMaterial = new PhysicMaterial ("ZeroFriction");
    41.             myMaterial.dynamicFriction = 0f;
    42.             myMaterial.staticFriction = 0f;
    43.             myMaterial.bounciness = 0f;
    44.             myMaterial.frictionCombine = PhysicMaterialCombine.Multiply;
    45.             myMaterial.bounceCombine = PhysicMaterialCombine.Average
    46. ;
    47.             gameObject.AddComponent <CapsuleCollider> ();
    48.             gameObject.GetComponent<CapsuleCollider> ().radius = 1f;
    49.             gameObject.GetComponent<CapsuleCollider> ().height = 1.68f;
    50.             gameObject.GetComponent<CapsuleCollider> ().material = myMaterial;
    51.        
    52.             gameObject.AddComponent <Rigidbody> ();
    53.             gameObject.GetComponent<Rigidbody> ().useGravity = false;
    54.         }
    55.     }
    56.     void Update () {
    57.  
    58.         // Angryboy: Hold right-mouse button to rotate
    59.         if (Input.GetMouseButtonDown (1)) {
    60.             isRotating = true;
    61.         }
    62.         if (Input.GetMouseButtonUp (1)) {
    63.             isRotating = false;
    64.         }
    65.         if (isRotating) {
    66.             // Made by LookForward
    67.             // Angryboy: Replaced min/max Y with numbers, not sure why we had variables in the first place
    68.             float rotationX = transform.localEulerAngles.y + Input.GetAxis ("Mouse X") * mouseSensitivity;
    69.             rotationY += Input.GetAxis ("Mouse Y") * mouseSensitivity;
    70.             rotationY = Mathf.Clamp (rotationY, -90, 90);
    71.             transform.localEulerAngles = new Vector3 (-rotationY, rotationX, 0.0f);
    72.         }
    73.  
    74.         //Keyboard commands
    75.         float f = 0.0f;
    76.         Vector3 p = GetBaseInput();
    77.         if (Input.GetKey (KeyCode.LeftShift)){
    78.             totalRun += Time.deltaTime;
    79.             p  = p * totalRun * shiftAdd;
    80.             p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
    81.             p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
    82.             p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    83.             // Angryboy: Use these to ensure that Y-plane is affected by the shift key as well
    84.             speedMultiplier = totalRun * shiftAdd * Time.deltaTime;
    85.             speedMultiplier = Mathf.Clamp(speedMultiplier, -maxShift, maxShift);
    86.         }
    87.         else{
    88.             totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
    89.             p = p * mainSpeed;
    90.             speedMultiplier = mainSpeed * Time.deltaTime; // Angryboy: More "correct" speed
    91.         }
    92.  
    93.         p = p * Time.deltaTime;
    94.  
    95.         // Angryboy: Removed key-press requirement, now perma-locked to the Y plane
    96.         Vector3 newPosition = transform.position;//If player wants to move on X and Z axis only
    97.         transform.Translate(p);
    98.         newPosition.x = transform.position.x;
    99.         newPosition.z = transform.position.z;
    100.  
    101.         // Angryboy: Manipulate Y plane by using Q/E keys
    102.         if (Input.GetKey (KeyCode.Q)){
    103.             newPosition.y += -speedMultiplier;
    104.         }
    105.         if (Input.GetKey (KeyCode.E)){
    106.             newPosition.y += speedMultiplier;
    107.         }
    108.  
    109.         transform.position = newPosition;
    110.     }
    111.  
    112.     // Angryboy: Can be called by other code to see if camera is rotating
    113.     // Might be useful in UI to stop accidental clicks while turning?
    114.     public bool amIRotating(){
    115.         return isRotating;
    116.     }
    117.  
    118.     private Vector3 GetBaseInput() { //returns the basic values, if it's 0 than it's not active.
    119.         Vector3 p_Velocity = new Vector3();
    120.         if (Input.GetKey (KeyCode.W)){
    121.             p_Velocity += new Vector3(0, 0 , 1);
    122.         }
    123.         if (Input.GetKey (KeyCode.S)){
    124.             p_Velocity += new Vector3(0, 0, -1);
    125.         }
    126.         if (Input.GetKey (KeyCode.A)){
    127.             p_Velocity += new Vector3(-1, 0, 0);
    128.         }
    129.         if (Input.GetKey (KeyCode.D)){
    130.             p_Velocity += new Vector3(1, 0, 0);
    131.         }
    132.         return p_Velocity;
    133.     }
    134. }
    I added a collision option so the camera can be contained if the developer wants it. I add a physic material to the collision object to keep the camera from spinning out of control when it hits a corner or multiple collision objects at the same time.
     
    Last edited: Jul 11, 2017
    YBOT likes this.
  29. astrojared

    astrojared

    Joined:
    Jan 7, 2017
    Posts:
    15
    I'm new to scripting in C# and how to use these scripts properly. Does someone here know how to import this script as a fly cam? Do I apply it to my camera?

    Thanks for the script and any advice!
     
  30. YBOT

    YBOT

    Joined:
    Feb 15, 2014
    Posts:
    2
    Hey @micah_3d , thanks heaps for adding the colliding functionality. I can not seem to get it working though. To replicate: I have a terrain with default settings and a camera with default settings and the script. I have also downloaded the characters package as you reference the material Zerofriction. What else do I need to do to get this to work?

    Thanks.
     
    Last edited: Aug 13, 2017
  31. Argonxx

    Argonxx

    Joined:
    Apr 16, 2017
    Posts:
    30
    This is very good guys. It wokrs perfect, but after pressing 'play' the camera view is always in some random position. Why does it change the rotation and angle itself?
    I have set Rotation to X:0 Y:180 Z:0, but it does not want to stay like this.
     
  32. anoluk

    anoluk

    Joined:
    Jun 18, 2017
    Posts:
    1
    @Argonxx, cant you put a breakpoint in and see where the rotation is getting setting again?
     
  33. grrava

    grrava

    Joined:
    Nov 11, 2012
    Posts:
    9
    I needed a fly camera script for quick debugging purposes and stumbled upon these scripts. Used it and worked out of the box! However I found the script to be really complicated for the simple things I needed it to do. And indeed the "random position at Play" is annoying.
    So I took the liberty to rewrite this script to do only flying around and nothing else (no physics and stuff)

    Code (CSharp):
    1. using UnityEngine;
    2. public class FlyCamera : MonoBehaviour
    3. {
    4.    private Vector3 _angles;
    5.    public float speed = 1.0f;
    6.    public float fastSpeed = 2.0f;
    7.    public float mouseSpeed = 4.0f;
    8.  
    9.    private void OnEnable() {
    10.        _angles = transform.eulerAngles;
    11.        Cursor.lockState = CursorLockMode.Locked;
    12.    }
    13.  
    14.    private void OnDisable() { Cursor.lockState = CursorLockMode.None; }
    15.  
    16.    private void Update() {
    17.        _angles.x -= Input.GetAxis("Mouse Y") * mouseSpeed;
    18.        _angles.y += Input.GetAxis("Mouse X") * mouseSpeed;
    19.        transform.eulerAngles = _angles;
    20.        float moveSpeed = Input.GetKey(KeyCode.LeftShift) ? fastSpeed : speed;
    21.        transform.position +=
    22.            Input.GetAxis("Horizontal") * moveSpeed * transform.right +
    23.            Input.GetAxis("Vertical") * moveSpeed * transform.forward;
    24.    }
    25. }
    Not saying this is a "better" script, but it suited my use case more and I thought I'd share it in case someone else is looking for a simpler script.
     
    maxneedle likes this.
  34. BitJunkie

    BitJunkie

    Joined:
    Jun 8, 2017
    Posts:
    1
    I tweaked grrava's simpler script to act more like UE4 editor fly cam, where you scroll with the mouse wheel to increase/decrease your flying speed, and have up/down controls on W/E. The code's ugly, but the speed controls are essential for getting close to examine things in detail and I probably won't get around to cleaning it.

    Code (CSharp):
    1. using UnityEngine;
    2. public class FlyCamera : MonoBehaviour
    3. {
    4.     private Vector3 _angles;
    5.     public float speed = 0.1f;
    6.     public float fastSpeed = 2.0f;
    7.     public float mouseSpeed = 4.0f;
    8.  
    9.     private void OnEnable()
    10.     {
    11.         //Debug.Log(speed);
    12.         speed = 0.1f;
    13.         _angles = transform.eulerAngles;
    14.         Cursor.lockState = CursorLockMode.Locked;
    15.     }
    16.  
    17.     private void OnDisable() { Cursor.lockState = CursorLockMode.None; }
    18.  
    19.     private void Update()
    20.     {
    21.         _angles.x -= Input.GetAxis("Mouse Y") * mouseSpeed;
    22.         _angles.y += Input.GetAxis("Mouse X") * mouseSpeed;
    23.         transform.eulerAngles = _angles;
    24.         float moveSpeed = Input.GetKey(KeyCode.LeftShift) ? fastSpeed : speed;
    25.         transform.position +=
    26.             Input.GetAxis("Horizontal") * moveSpeed * transform.right +
    27.             Input.GetAxis("Vertical") * moveSpeed * transform.forward;
    28.  
    29.  
    30.         // addition: Scroll wheel speed control
    31.         if (Input.GetAxis("Mouse ScrollWheel") > 0f) // forward
    32.         {   speed *= 2; }
    33.         else if (Input.GetAxis("Mouse ScrollWheel") < 0f) // backwards
    34.         {   speed *= 0.5f;
    35.             //Debug.Log(speed);
    36.         }
    37.  
    38.         float upDownMultiplier = 0.5f;
    39.         if (Input.GetKey(KeyCode.E))
    40.         { transform.position += moveSpeed * transform.up * upDownMultiplier; }
    41.  
    42.         if (Input.GetKey(KeyCode.Q))
    43.         { transform.position -= moveSpeed * transform.up * upDownMultiplier; }
    44.  
    45.     }
    46. }