Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

Мне нужен совет, у меня есть класс CameraController using Cinemachine; using…

  1. User

    Мне нужен совет, у меня есть класс CameraController

    using Cinemachine; using UnityEditor; using UnityEngine; using UnityEngine.Serialization;

    public class CameraController : MonoBehaviour { [SerializeField] private InputHandler inputHandler; [SerializeField] private InputProvider inputProvider; [SerializeField] private CinemachineVirtualCamera virtualCamera; private CinemachineFramingTransposer _framingTransposer;

    public bool isFreezing;
    
    
    [SerializeField] [Tooltip("Check to make the controller be independent on the Time Scale.")]
    public bool independentTimeScale = true;
    
    public bool IsDragging { get; private set; }
    public bool IsMoving { get; private set; }
    public bool IsRotating { get; private set; }
    public bool IsEdgeScrolling { get; private set; }
    
    
    [SerializeField] [Space(10)] [Header("Move")]
    private float moveSpeed;
    
    [field: SerializeField] public bool AllowMove { get; set; }
    
    
    [FormerlySerializedAs("_dragStartPosition")]
    [SerializeField]
    [Space(10)]
    [Header("Drag")]
    [Tooltip("Режет дистанцию если драг слишком большой")]
    private float maxDragMagnitude;
    
    private Vector3 _dragStartPosition;
    
    [Tooltip("На сколько сильно увеличивать движение после того как игрок отпустил пкм. 1 - без изменений")]
    [SerializeField]
    private float dragPanScale;
    
    [Tooltip("На сколько сильно уменьшать дистанцию после того как игрок отпустил пкм. 1 - без изменений")]
    [SerializeField, Range(1, 10)]
    private float dragPanDeltaReduce;
    
    [SerializeField] private float cameraDragPanSmoothTime;
    [SerializeField] private float cameraDragSmoothTime;
    [field: SerializeField] public bool AllowDrag { get; set; }
    
    private Vector3 _lastDragDelta;
    
    private Vector3 _targetCameraPosition;
    private Vector3 _currentCameraPosition;
    
    
    [SerializeField] [Space(10)] [Header("Zoom")]
    private float cameraZoomSpeed;
    
    
    private float _currentCameraZoom;
    private float _cameraZoomSmoothDampVelRef;
    
    [SerializeField] private float cameraZoomMin;
    [SerializeField] private float cameraZoomMax;
    [SerializeField] private float cameraZoomSmoothTime = 7f;
    
    [field: SerializeField] public bool AllowZoom { get; set; }
    
    [SerializeField] [Space(10)] [Header("Rotate")]
    private bool mouseLockOnRotate = true;
    
    [SerializeField] private float rotateSpeed;
    [SerializeField] private float cameraTiltMin;
    [SerializeField] private float cameraTiltMax;
    [SerializeField] private bool invertMouseHorizontal;
    [SerializeField] private bool invertMouseVertical;
    [SerializeField] private float cameraTargetRotateSmoothTime;
    
    private float _targetCameraRotate;
    private float _targetCameraTilt;
    private float _currentCameraRotate;
    private float _currentCameraTilt;
    private float _cameraRotateSmoothDampVelRef;
    private float _cameraTiltSmoothDampVelRef;
    
    [field: SerializeField] public bool AllowRotate { get; set; }
    
    [FormerlySerializedAs("_edgeScrollingSpeed")] [Space(10)] [Header("Edge Scrolling")] [SerializeField]
    private float edgeScrollingSpeed;
    
    [SerializeField] private float edgeScrollingAreaOffset;
    [field: SerializeField] public bool AllowEdgeScrolling { get; set; }
    
    
    [SerializeField] [Space(10)] [Header("Boundaries")] [Range(-10000, 0)]
    public float boundaryMinX = -500f;
    
    [SerializeField, Range(0, 10000)] public float boundaryMaxX = 500f;
    
    [SerializeField, Range(-10000, 0)] public float boundaryMinZ = -500f;
    
    [SerializeField, Range(0, 10000)] public float boundaryMaxZ = 500f;
    
    [field: SerializeField] public bool EnableBoundaries { get; set; } = true;
    
    private void Start()
    {
        if (!inputHandler)
            inputHandler = GetComponent<InputHandler>();
    
        if (!inputProvider)
            inputProvider = GetComponent<InputProvider>();
    
        _framingTransposer = virtualCamera.GetCinemachineComponent<CinemachineFramingTransposer>();
        _currentCameraZoom = _framingTransposer.m_CameraDistance;
    
        _currentCameraTilt = Mathf.Lerp(cameraTiltMin, cameraTiltMax, 0.5f);
        _targetCameraTilt = _currentCameraTilt;
        _targetCameraRotate = transform.eulerAngles.y;
    
        inputHandler.OnDragStop += () =>
        {
            IsDragging = false;
            // _currentCameraPosition = transform.position;
            // _targetCameraPosition = transform.position;
    
    
            var moveInput = _lastDragDelta / dragPanDeltaReduce * dragPanScale;
    
            _targetCameraPosition += moveInput;
        };
    
        inputHandler.OnDrag += dragPosition =>
        {
            if (isFreezing) return;
            if (!AllowDrag) return;
            if (IsRotating) return;
    
            if (!IsDragging)
            {
                //Да, OnDragStart для пидоров
                IsDragging = true;
                _dragStartPosition = dragPosition;
                
                _currentCameraPosition = transform.position;
                _targetCameraPosition = transform.position;
            }
    
            var dragDelta = _dragStartPosition - dragPosition;
    
    
            if (dragDelta.magnitude > maxDragMagnitude)
            {
                dragDelta = dragDelta.normalized * maxDragMagnitude;
            }
    
            // transform.position += dragDelta;
    
            _targetCameraPosition += dragDelta;
            _lastDragDelta = dragDelta;
        };
    
        inputHandler.OnMove += inputVector =>
        {
            if (isFreezing) return;
            if (!AllowMove) return;
    
            var moveDirection = GetRelativeDirection(inputVector);
    
            var moveInput = moveDirection * (moveSpeed * RelativeSpeed * Time.deltaTime);
    
    
            transform.position += moveInput;
        };
    
        inputHandler.OnMoveStart += () => { IsMoving = true; };
    
        inputHandler.OnMoveStop += () =>
        {
            IsMoving = false;
            _currentCameraPosition = transform.position;
            _targetCameraPosition = transform.position;
        };
    
        inputHandler.OnRotate += inputVector =>
        {
            if (isFreezing) return;
            if (!AllowRotate) return;
            if (IsDragging) return;
    
            IsRotating = true;
            if (mouseLockOnRotate) LockMouse(true);
    
    
            if (inputVector.x != 0)
            {
                _targetCameraRotate += inputVector.x * rotateSpeed * (invertMouseHorizontal ? -1 : 1);
            }
    
            if (inputVector.y != 0)
            {
                _targetCameraTilt -= inputVector.y * rotateSpeed * (invertMouseVertical ? -1 : 1);
                _targetCameraTilt = Mathf.Clamp(_targetCameraTilt, cameraTiltMin, cameraTiltMax);
            }
        };
    
        inputHandler.OnRotateStop += () =>
        {
            IsRotating = false;
            if (mouseLockOnRotate) LockMouse(false);
        };
    
        inputHandler.OnZoom += value =>
        {
            if (isFreezing) return;
            if (!AllowZoom) return;
    
    
            _currentCameraZoom -= value * cameraZoomSpeed;
            _currentCameraZoom = Mathf.Clamp(_currentCameraZoom, cameraZoomMin, cameraZoomMax);
        };
    }
    
    private void LockMouse(bool lockMouse)
    {
        Cursor.lockState = lockMouse ? CursorLockMode.Locked : CursorLockMode.None;
        Cursor.visible = !lockMouse;
    }
    
    
    private void Update()
    {
        if (isFreezing) return;
    
        ProcessRotate();
        ProcessDrag();
        ProcessDragPan();
        ProcessZoom();
        HandleEdgeScrolling();
    }
    
    private void LateUpdate()
    {
        if (!EnableBoundaries) return;
        HandleBoundaries();
    }
    
    private void ProcessDrag()
    {
        if (!IsDragging) return;
    
        _currentCameraPosition = Vector3.Lerp(_currentCameraPosition, _targetCameraPosition,
            cameraDragSmoothTime / 100);
    
        transform.position = _currentCameraPosition;
    
        _currentCameraPosition = transform.position;
        _targetCameraPosition = transform.position;
    }
    

    #if UNITY_EDITOR

    private void ProcessDragPan()
    {
        if (IsDragging)
        {
            return;
        }
    
        if (IsMoving || IsRotating || IsEdgeScrolling)
        {
            _currentCameraPosition = transform.position;
            _targetCameraPosition = transform.position;
    
            return;
        }
    
        _currentCameraPosition = Vector3.Lerp(_currentCameraPosition, _targetCameraPosition,
            cameraDragPanSmoothTime / 100);
    
        transform.position = _currentCameraPosition;
    }
    
    private void OnDrawGizmosSelected()
    {
        if (!EnableBoundaries) return;
    
        Handles.color = Color.green;
        Handles.DrawLine(new Vector3(boundaryMinX, 0, boundaryMinZ), new Vector3(boundaryMaxX, 0, boundaryMinZ));
        Handles.DrawLine(new Vector3(boundaryMaxX, 0, boundaryMinZ), new Vector3(boundaryMaxX, 0, boundaryMaxZ));
        Handles.DrawLine(new Vector3(boundaryMinX, 0, boundaryMinZ), new Vector3(boundaryMinX, 0, boundaryMaxZ));
        Handles.DrawLine(new Vector3(boundaryMinX, 0, boundaryMaxZ), new Vector3(boundaryMaxX, 0, boundaryMaxZ));
        Handles.Label(new Vector3(boundaryMinX, 0, 0), $"Min X: {boundaryMinX}");
        Handles.Label(new Vector3(boundaryMaxX, 0, 0), $"Max X: {boundaryMaxX}");
        Handles.Label(new Vector3(0, 0, boundaryMinZ), $"Min Z: {boundaryMinZ}");
        Handles.Label(new Vector3(0, 0, boundaryMaxZ), $"Max Z: {boundaryMaxZ}");
    }
    

    #endif

    private void HandleBoundaries()
    {
        if (!EnableBoundaries) return;
    
        var position = transform.position;
    
        if (position.x > boundaryMaxX)
            transform.position = new Vector3(boundaryMaxX, transform.position.y, position.z);
        if (position.x < boundaryMinX)
            transform.position = new Vector3(boundaryMinX, transform.position.y, position.z);
        if (position.z > boundaryMaxZ)
            transform.position = new Vector3(transform.position.x, position.y, boundaryMaxZ);
        if (position.z < boundaryMinZ)
            transform.position = new Vector3(transform.position.x, position.y, boundaryMinZ);
    }
    
    private void HandleEdgeScrolling()
    {
        if (!AllowEdgeScrolling || IsDragging || IsMoving)
        {
            IsEdgeScrolling = false;
            return;
        }
    
    
        var mousePosition = inputProvider.MousePosition();
    
    
        var leftDistance = mousePosition.x;
        var rightDistance = Screen.width - mousePosition.x;
        var bottomDistance = mousePosition.y;
        var topDistance = Screen.height - mousePosition.y;
    
    
        var inputDirection = Vector3.zero;
        if (leftDistance < edgeScrollingAreaOffset)
        {
            inputDirection += Vector3.left;
        }
        else if (rightDistance < edgeScrollingAreaOffset)
        {
            inputDirection += Vector3.right;
        }
    
        if (bottomDistance < edgeScrollingAreaOffset)
        {
            inputDirection -= Vector3.forward;
        }
        else if (topDistance < edgeScrollingAreaOffset)
        {
            inputDirection += Vector3.forward;
        }
    
    
        if (inputDirection == Vector3.zero)
        {
            IsEdgeScrolling = false;
            return;
        }
    
        IsEdgeScrolling = true;
    
        var moveDirection = GetRelativeDirection(inputDirection);
        transform.position += moveDirection * (edgeScrollingSpeed * RelativeSpeed * Time.deltaTime);
    }
    
    private void ProcessZoom()
    {
        if (!AllowZoom) return;
    
    
        _framingTransposer.m_CameraDistance = Mathf.SmoothDamp(_framingTransposer.m_CameraDistance,
            _currentCameraZoom, ref _cameraZoomSmoothDampVelRef, cameraZoomSmoothTime / 100, Mathf.Infinity,
            GetTimeScale());
    }
    
    private void ProcessRotate()
    {
        _currentCameraRotate = Mathf.SmoothDamp(_currentCameraRotate, _targetCameraRotate,
            ref _cameraRotateSmoothDampVelRef, cameraTargetRotateSmoothTime / 100, Mathf.Infinity, GetTimeScale());
        _currentCameraTilt = Mathf.SmoothDamp(_currentCameraTilt, _targetCameraTilt,
            ref _cameraTiltSmoothDampVelRef, cameraTargetRotateSmoothTime / 100, Mathf.Infinity, GetTimeScale());
    
    
        virtualCamera.transform.eulerAngles = new Vector3(_currentCameraTilt, _currentCameraRotate, 0);
    }
    
    private Vector3 GetRelativeDirection(Vector3 direction)
    {
        var camForward = virtualCamera.transform.forward;
        var camRight = virtualCamera.transform.right;
        camForward.y = 0f;
        camRight.y = 0f;
        camForward.Normalize();
        camRight.Normalize();
        return (camForward * direction.z) + (camRight * direction.x);
    }
    
    public float RelativeSpeed => _framingTransposer.m_CameraDistance / cameraZoomMin;
    
    public float GetTimeScale() => independentTimeScale ? Time.unscaledDeltaTime : Time.deltaTime;
    

    }

    класс InputHandler

    using UnityEngine; using UnityEngine.Events;

    public class InputHandler : MonoBehaviour { private InputProvider _inputProvider; [SerializeField] private Camera myCamera; [SerializeField] private float planeY;

    public event UnityAction<Vector3> OnDrag;
    public event UnityAction<Vector3> OnDragStart;
    public event UnityAction OnDragStop;
    
    public event UnityAction OnZoomStart;
    public event UnityAction<float> OnZoom;
    public event UnityAction OnZoomStop;
    
    public event UnityAction<Vector3> OnMove;
    public event UnityAction OnMoveStart;
    public event UnityAction OnMoveStop;
    
    public event UnityAction<Vector3> OnRotate;
    public event UnityAction OnRotateStop;
    
    
    
    public void InvokeZoom(float param)
    {
        OnZoom?.Invoke(param);
    }
    
    private void Start()
    {
        _inputProvider = GetComponent<InputProvider>();
        
        InitActions();
    }
    
    private void InitActions()
    {
        // --- MOBILE --- 
        _inputProvider.InputActions.Default.FirstTouchContact.started += _ =>
        {
            OnDragStart?.Invoke(GetHitPoint(_inputProvider.FirstTouch()));
        };
    
        _inputProvider.InputActions.Default.FirstTouchContact.canceled += _ => { OnDragStop?.Invoke(); };
    
        _inputProvider.InputActions.Default.SecondTouchContact.started += context => { };
    
        // --- PC --- 
        _inputProvider.InputActions.Default.Drag.started += _ =>
        {
            OnDragStart?.Invoke(GetHitPoint(_inputProvider.MousePosition()));
        };
    
        _inputProvider.InputActions.Default.Drag.canceled += _ => { OnDragStop?.Invoke(); };
    
        _inputProvider.InputActions.Default.Zoom.started += _ => { OnZoomStart?.Invoke(); };
    
        _inputProvider.InputActions.Default.Zoom.canceled += _ => { OnZoomStop?.Invoke(); };
    
        _inputProvider.InputActions.Default.Zoom.performed += context =>
        {
            OnZoom?.Invoke(context.ReadValue<float>());
        };
    
        _inputProvider.InputActions.Default.Rotate.canceled += _ => { OnRotateStop?.Invoke(); };
    
        _inputProvider.InputActions.Default.Move.canceled += context => { OnMoveStop?.Invoke(); };
    
        _inputProvider.InputActions.Default.Move.started += context => { OnMoveStart?.Invoke(); };
    }
    
    private void Update()
    {
        HandleMiddleMouse();
        HandleFirstTouch();
        HandleKeyboardMove();
        HandleRotate();
    }
    
    private void HandleRotate()
    {
        if (!_inputProvider.RightButtonInput()) return;
    
        OnRotate?.Invoke(_inputProvider.MouseInput());
    }
    
    private void HandleMiddleMouse()
    {
        if (!_inputProvider.DragButtonInput()) return;
        OnDrag?.Invoke(GetHitPoint(_inputProvider.MousePosition()));
    }
    
    private void HandleFirstTouch()
    {
        if (!_inputProvider.IsFirstTouch()) return;
        OnDrag?.Invoke(GetHitPoint(_inputProvider.FirstTouch()));
    }
    
    
    private void HandleKeyboardMove()
    {
        var keyboardInput = _inputProvider.MovementInput();
        if (keyboardInput == Vector2.zero) return;
        var vectorChange = new Vector3(keyboardInput.x, 0, keyboardInput.y);
    
        OnMove?.Invoke(vectorChange);
    }
    
    public Vector3 GetHitPoint(Vector3 position)
    {
        var mousePositionInScreen = position;
        var ray = myCamera.ScreenPointToRay(mousePositionInScreen);
        var distanceToPlane = (planeY - ray.origin.y) / ray.direction.y;
        var cursorPositionOnPlane = ray.origin + ray.direction * distanceToPlane;
        return cursorPositionOnPlane;
    }
    

    }

    Класс InputProvider

    using UnityEngine;

    public class InputProvider : MonoBehaviour { public InputActions InputActions;

    private void Awake()
    {
        InputActions = new InputActions();
        InputActions.Enable();
    }
    
    public bool DragButtonInput() => InputActions.Default.Drag.IsPressed();
    
    public Vector2 MouseInput() => InputActions.Default.Mouse.ReadValue<Vector2>();
    
    public Vector2 FirstTouch() => InputActions.Default.FirstTouch.ReadValue<Vector2>();
    public bool IsFirstTouch() => InputActions.Default.FirstTouchContact.IsPressed();
    public bool IsSecondTouch() => InputActions.Default.SecondTouchContact.IsPressed();
    
    public Vector2 SecondTouch() => InputActions.Default.SecondTouch.ReadValue<Vector2>();
    
    public Vector2 MousePosition() => InputActions.Default.MousePosition.ReadValue<Vector2>();
    
    public Vector2 MovementInput() => InputActions.Default.Move.ReadValue<Vector2>();
    
    public bool RightButtonInput() => InputActions.Default.Rotate.IsPressed();
    
    public float ZoomInput() => InputActions.Default.Zoom.ReadValue<float>();
    
    public bool HeightUpButtonInput() => InputActions.Default.HeightUp.IsPressed();
    
    public bool HeightDownButtonInput() => InputActions.Default.HeightDown.IsPressed();
    
    public bool RotateRightButtonInput() => InputActions.Default.RotateRight.IsPressed();
    
    public bool RotateLeftButtonInput() => InputActions.Default.RotateLeft.IsPressed();
    

    }

    Проблема в том, что это реализация для пк. Нужна ещё реализация для телефонов, но по большей части код для пк и смартфонов одинаковый, есть только небольшие различия. Также параметры по типу скорости должны быть разными для телефонов и пк. Подскажи, как лучше сделать?

  2. Assistant

    Для решения вашей задачи рекомендуется использовать подход, при котором различия между версиями для ПК и смартфонов скрыты за абстракциями и не требуют дублирования большого объема кода. Можете использовать полиморфизм и интерфейсы/абстрактные классы.

    Основной стратегией здесь будет создание общего интерфейса или базового класса для обработки ввода и использования конкретных реализаций для ПК и смартфонов. В зависимости от платформы вы сможете выбрать правильную реализацию. Также рекомендуется использовать ScriptableObjects для хранения конфигураций, таких как параметры скорости, чтобы их можно было легко настраивать и менять.

    Пример реализации

    1. Интерфейс для обработки ввода:

    public interface IInputHandler
    {
        event UnityAction<Vector3> OnDrag;
        event UnityAction<Vector3> OnDragStart;
        event UnityAction OnDragStop;
    
        event UnityAction OnZoomStart;
        event UnityAction<float> OnZoom;
        event UnityAction OnZoomStop;
    
        event UnityAction<Vector3> OnMove;
        event UnityAction OnMoveStart;
        event UnityAction OnMoveStop;
    
        event UnityAction<Vector3> OnRotate;
        event UnityAction OnRotateStop;
    
        void ProcessInput();
    }
    

    2. Реализация для ПК и мобильных устройств:

    public class PCInputHandler : MonoBehaviour, IInputHandler
    {
        private InputProvider _inputProvider;
        [SerializeField] private Camera myCamera;
        [SerializeField] private float planeY;
    
        public event UnityAction<Vector3> OnDrag;
        public event UnityAction<Vector3> OnDragStart;
        public event UnityAction OnDragStop;
        // Остальные события...
    
        private void Start()
        {
            _inputProvider = GetComponent<InputProvider>();
            // Инициализация событий...
        }
    
        public void ProcessInput()
        {
            HandleMiddleMouse();
            HandleKeyboardMove();
            HandleRotate();
        }
    
        private void HandleMiddleMouse() { /*Your current implementation*/ }
        private void HandleRotate() { /*Your current implementation*/ }
        private void HandleKeyboardMove() { /*Your current implementation*/ }
        // ...
    }
    
    public class MobileInputHandler : MonoBehaviour, IInputHandler
    {
        private InputProvider _inputProvider;
        [SerializeField] private Camera myCamera;
        [SerializeField] private float planeY;
    
        public event UnityAction<Vector3> OnDrag;
        public event UnityAction<Vector3> OnDragStart;
        public event UnityAction OnDragStop;
        // Остальные события...
    
        private void Start()
        {
            _inputProvider = GetComponent<InputProvider>();
            // Инициализация событий...
        }
    
        public void ProcessInput()
        {
            HandleFirstTouch();
            HandleZoom();
            HandleMove();
        }
    
        private void HandleFirstTouch() { /*Your current implementation*/ }
        private void HandleZoom() { /*Implementation for zoom on mobile*/ }
        private void HandleMove() { /*Implementation for move on mobile*/ }
        // ...
    }
    

    3. Использование разных конфигураций:

    Создайте ScriptableObject для конфигураций. Например:

    [CreateAssetMenu(fileName = "CameraConfig", menuName = "Configs/Camera")]
    public class CameraConfig : ScriptableObject
    {
        public float moveSpeed;
        public float dragPanScale;
        public float cameraZoomSpeed;
        // Остальные настройки...
    }
    

    Затем в CameraController используйте этот конфигурационный объект:

    public class CameraController : MonoBehaviour
    {
        [SerializeField] private CameraConfig pcConfig;
        [SerializeField] private CameraConfig mobileConfig;
        private CameraConfig config;
    
        [SerializeField] private InputHandler inputHandler;
        [SerializeField] private InputProvider inputProvider;
        [SerializeField] private CinemachineVirtualCamera virtualCamera;
        private CinemachineFramingTransposer _framingTransposer;
    
        // Другие переменные...
    
        private void Start()
        {
            config = Application.isMobilePlatform ? mobileConfig : pcConfig;
            // Использование config для настройки скоростей и других параметров
              
            // Пример использования
            moveSpeed = config.moveSpeed;
            dragPanScale = config.dragPanScale;
            cameraZoomSpeed = config.cameraZoomSpeed;
    
            inputHandler = Application.isMobilePlatform
                ? (InputHandler)gameObject.AddComponent<MobileInputHandler>()
                : (InputHandler)gameObject.AddComponent<PCInputHandler>();
    
            // Подпишитесь на события inputHandler и добавьте остальной код инициализации
        }
    
        private void Update()
        {
            inputHandler?.ProcessInput();
            // Остальные обновления
        }
    
        // Остальной код...
    }
    

    Заключение

    Эта архитектура позволяет вам легко расширять и поддерживать код. Реализации для ПК и мобильных устройств изолированы друг от друга, и если вы решите внести изменения, вам не придется изменять много кода или дублировать его.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.