FreeCamera.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using UnityEngine;
  2. public class FreeCamera : MonoBehaviour
  3. {
  4. private Vector3 MousePos;
  5. [SerializeField] private float MoveAccelerationSpeed;
  6. [SerializeField] private float MoveSpeed;
  7. [SerializeField] private float RotateSpeed;
  8. private Vector3 Velocity;
  9. private void Update()
  10. {
  11. Velocity.z = Mathf.MoveTowards(Velocity.z, Input.GetAxis("Vertical") * MoveSpeed,
  12. MoveAccelerationSpeed * Time.deltaTime);
  13. Velocity.x = Mathf.MoveTowards(Velocity.x, Input.GetAxis("Horizontal") * MoveSpeed,
  14. MoveAccelerationSpeed * Time.deltaTime);
  15. Velocity.y = Mathf.MoveTowards(Velocity.y,
  16. (Input.GetKey(KeyCode.E) ? 1 : Input.GetKey(KeyCode.Q) ? -1 : 0) * MoveSpeed * 0.3f,
  17. MoveAccelerationSpeed * Time.deltaTime);
  18. transform.position += transform.TransformDirection(Velocity);
  19. var mousePosDelta = Input.mousePosition - MousePos;
  20. MousePos = Input.mousePosition;
  21. transform.rotation *= Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * RotateSpeed, Vector3.left);
  22. transform.rotation *= Quaternion.AngleAxis(Input.GetAxis("Mouse X") * RotateSpeed, Vector3.up);
  23. var eulerAngles = transform.eulerAngles;
  24. eulerAngles.z = 0;
  25. transform.eulerAngles = eulerAngles;
  26. if (Input.GetKey(KeyCode.LeftAlt))
  27. {
  28. Cursor.visible = true;
  29. Cursor.lockState = CursorLockMode.None;
  30. }
  31. else
  32. {
  33. Cursor.visible = false;
  34. Cursor.lockState = CursorLockMode.Locked;
  35. }
  36. Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView + Input.mouseScrollDelta.y, 5, 150);
  37. }
  38. }