CameraController.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 = 20;
  8. private Vector2 mouseOrigin;
  9. private Vector3 cameraOrigin;
  10. private bool drag = false;
  11. // Start is called once before the first execution of Update after the MonoBehaviour is created
  12. private void Start()
  13. {
  14. }
  15. private void Update()
  16. {
  17. if (Mouse.current.scroll.value != Vector2.zero)
  18. {
  19. distance -= Mouse.current.scroll.value.y;
  20. UpdateCamera();
  21. }
  22. }
  23. // Update is called once per frame
  24. private void LateUpdate()
  25. {
  26. if (Mouse.current.rightButton.isPressed)
  27. {
  28. var mousePosition = Mouse.current.position.value;
  29. if (drag == false)
  30. {
  31. drag = true;
  32. mouseOrigin = mousePosition;
  33. cameraOrigin = Camera.main.transform.position;
  34. }
  35. }
  36. else
  37. {
  38. drag = false;
  39. }
  40. if (drag)
  41. {
  42. var mousePosition = Mouse.current.position.value;
  43. var mouseDiff = mouseOrigin - mousePosition;
  44. var mouseDiff3 = (Vector3)mouseDiff;
  45. mouseOrigin = mousePosition;
  46. Camera.main.transform.Translate(mouseDiff3);
  47. Camera.main.transform.rotation = Quaternion.LookRotation(player.transform.position - Camera.main.transform.position);
  48. UpdateCamera();
  49. }
  50. }
  51. private void UpdateCamera()
  52. {
  53. var direction = Camera.main.transform.position - player.transform.position;
  54. var normal = Vector3.Normalize(direction);
  55. Camera.main.transform.position = normal * distance;
  56. }
  57. }