P_V_D

Unity Free Flight Camera

Jun 30th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.27 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class FreeFlightCamera : MonoBehaviour
  4. {
  5.     public static readonly string[] Description = new string[]
  6.     {
  7.         "WASD to move",
  8.         "RMB to rotate",
  9.         "Space, Ctrl to jump",
  10.         "Shift to accelerate"
  11.     };
  12.  
  13.     public bool DrawInfo = true;
  14.     public float LiniarSpeed = 10;
  15.     public float AngularRotationArc = 130;
  16.  
  17.     private Vector3 _lastMousePosition;
  18.  
  19.     private void SimulateMotion(float deltaTime)
  20.     {
  21.         var motion = Vector3.zero;
  22.         var jump = Vector3.zero;
  23.         if (Input.GetKey(KeyCode.W)) motion.z = 1;
  24.         if (Input.GetKey(KeyCode.S)) motion.z = -1;
  25.         if (Input.GetKey(KeyCode.D)) motion.x = 1;
  26.         if (Input.GetKey(KeyCode.A)) motion.x = -1;
  27.         if (Input.GetKey(KeyCode.Space)) jump.y = 1;
  28.         if (Input.GetKey(KeyCode.LeftControl)) jump.y = -1;
  29.         motion = deltaTime * LiniarSpeed * motion.normalized;
  30.         jump = deltaTime * LiniarSpeed * jump;
  31.         if (Input.GetKey(KeyCode.LeftShift))
  32.         {
  33.             motion *= 5;
  34.             jump *= 5;
  35.         }
  36.         transform.Translate(motion);
  37.         transform.Translate(jump, Space.World);
  38.     }
  39.  
  40.     private void SimulateRotation()
  41.     {
  42.         if (Input.GetMouseButtonDown(1))
  43.             _lastMousePosition = Input.mousePosition;
  44.         if (Input.GetMouseButton(1))
  45.         {
  46.             var mouseDelta = Input.mousePosition - _lastMousePosition;
  47.             var x = Mathf.Abs(mouseDelta.x / Screen.width) * AngularRotationArc * Mathf.Sign(mouseDelta.x);
  48.             var y = -Mathf.Abs(mouseDelta.y / Screen.height) * AngularRotationArc * Mathf.Sign(mouseDelta.y);
  49.             transform.Rotate(Vector3.right, y);
  50.             transform.Rotate(0, x, 0, Space.World);
  51.             _lastMousePosition = Input.mousePosition;
  52.         }
  53.     }
  54.  
  55.     private void Update()
  56.     {
  57.         SimulateMotion(Time.deltaTime);
  58.         SimulateRotation();
  59.     }
  60.  
  61.     private void OnGUI()
  62.     {
  63.         if (DrawInfo) DrawTextLines(Description);
  64.     }
  65.  
  66.     private void DrawTextLines(string[] lines)
  67.     {
  68.         var lineHeight = 24;
  69.         var lineWidth = 256;
  70.         for(var i = 0; i < lines.Length; i++)
  71.             GUI.TextField(new Rect(0, lineHeight * i, lineWidth, lineHeight), lines[i]);
  72.     }
  73. }
Add Comment
Please, Sign In to add comment