| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using UnityEngine;
- using UnityEngine.InputSystem;
- public class CameraController : MonoBehaviour
- {
- public GameObject player;
- public Vector3 offset;
- public float distance = 5;
- public float minDistance = 2;
- public float mouseSensitivity = 0.5f;
- private Vector2 mouseOrigin;
- private bool drag = false;
- // Start is called once before the first execution of Update after the MonoBehaviour is created
- private void Start()
- {
- }
- private void Update()
- {
- if (Mouse.current.scroll.value != Vector2.zero)
- {
- distance -= Mouse.current.scroll.value.y;
- distance = Mathf.Max(distance, minDistance);
- UpdateCamera();
- }
- }
- // Update is called once per frame
- private void LateUpdate()
- {
- if (Mouse.current.rightButton.isPressed)
- {
- var mousePosition = Mouse.current.position.value;
- if (drag == false)
- {
- drag = true;
- mouseOrigin = mousePosition;
- }
- }
- else
- {
- drag = false;
- }
- if (drag)
- {
- var mousePosition = Mouse.current.position.value;
- var mouseDiff = mouseOrigin - mousePosition;
- var mouseDiff3 = (Vector3)mouseDiff;
- mouseOrigin = mousePosition;
- Camera.main.transform.Translate(mouseDiff3 * mouseSensitivity * distance / 50);
- Camera.main.transform.rotation = Quaternion.LookRotation(player.transform.position - Camera.main.transform.position);
- UpdateCamera();
- }
- }
- private void UpdateCamera()
- {
- var direction = Camera.main.transform.position - player.transform.position;
- var normal = Vector3.Normalize(direction);
- Camera.main.transform.position = normal * distance;
- }
- }
|