CameraController.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEngine;
  2. using UnityEngine.InputSystem;
  3. public class CameraController : MonoBehaviour
  4. {
  5. public GameObject player;
  6. public Vector3 offset;
  7. public float distance = 5;
  8. public float minDistance = 2;
  9. public float mouseSensitivity = 0.5f;
  10. private Vector2 mouseOrigin;
  11. private bool drag = false;
  12. // Start is called once before the first execution of Update after the MonoBehaviour is created
  13. private void Start()
  14. {
  15. }
  16. private void Update()
  17. {
  18. if (Mouse.current.scroll.value != Vector2.zero)
  19. {
  20. distance -= Mouse.current.scroll.value.y;
  21. distance = Mathf.Max(distance, minDistance);
  22. UpdateCamera();
  23. }
  24. }
  25. // Update is called once per frame
  26. private void LateUpdate()
  27. {
  28. if (Mouse.current.rightButton.isPressed)
  29. {
  30. var mousePosition = Mouse.current.position.value;
  31. if (drag == false)
  32. {
  33. drag = true;
  34. mouseOrigin = mousePosition;
  35. }
  36. }
  37. else
  38. {
  39. drag = false;
  40. }
  41. if (drag)
  42. {
  43. var mousePosition = Mouse.current.position.value;
  44. var mouseDiff = mouseOrigin - mousePosition;
  45. var mouseDiff3 = (Vector3)mouseDiff;
  46. mouseOrigin = mousePosition;
  47. Camera.main.transform.Translate(mouseDiff3 * mouseSensitivity * distance / 50);
  48. Camera.main.transform.rotation = Quaternion.LookRotation(player.transform.position - Camera.main.transform.position);
  49. UpdateCamera();
  50. }
  51. }
  52. private void UpdateCamera()
  53. {
  54. var direction = Camera.main.transform.position - player.transform.position;
  55. var normal = Vector3.Normalize(direction);
  56. Camera.main.transform.position = normal * distance;
  57. }
  58. }