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

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

    Шаг 1: Использование директив препроцессора

    Используйте директивы препроцессора (#if UNITY_STANDALONE, #if UNITY_IOS, #if UNITY_ANDROID), чтобы разделить код для каждой платформы. Это позволит вам внедрять разные настройки для ПК и мобильных устройств.

    Шаг 2: Платформо-зависимые настройки

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

    Шаг 3: Разделение кода ввода

    Объедините мобильные и ПК-сооружения ввода в один обрабатывающий класс (например, InputProvider или InputHandler), чтобы использовать их одинаковым способом.

    Пример реализации этого подхода

    Платформозависимые настройки

    Создайте два ScriptableObject для хранения конфигураций:

    [CreateAssetMenu(menuName = "Settings/PC Camera Settings")]
    public class PcCameraSettings : ScriptableObject
    {
        public float moveSpeed;
        public float rotateSpeed;
        public float cameraZoomSpeed;
        public float edgeScrollingSpeed;
        // Add other settings specific to PC
    }
    
    [CreateAssetMenu(menuName = "Settings/Mobile Camera Settings")]
    public class MobileCameraSettings : ScriptableObject
    {
        public float moveSpeed;
        public float rotateSpeed;
        public float cameraZoomSpeed;
        public float edgeScrollingSpeed;
        // Add other settings specific to mobile
    }
    

    Объединение ввода

    Обновите ваш InputProvider, чтобы он различал мобильные и ПК-команды:

    public class InputProvider : MonoBehaviour
    {
        public InputActions InputActions;
    
        private void Awake()
        {
            InputActions = new InputActions();
            InputActions.Enable();
        }
    
    #if UNITY_STANDALONE || UNITY_WEBGL
        // ПК Ввод
        public bool DragButtonInput() => InputActions.Default.Drag.IsPressed();
        public Vector2 MouseInput() => InputActions.Default.Mouse.ReadValue<Vector2>();
        public Vector2 MousePosition() => InputActions.Default.MousePosition.ReadValue<Vector2>();
        public bool RightButtonInput() => InputActions.Default.Rotate.IsPressed();
        public Vector2 MovementInput() => InputActions.Default.Move.ReadValue<Vector2>();
        public float ZoomInput() => InputActions.Default.Zoom.ReadValue<float>();
    #else
        // Мобильный Ввод
        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>();
    #endif
    }
    

    CameraController

    Используйте настройки для конкретной платформы в вашем CameraController:

    public class CameraController : MonoBehaviour
    {
        [SerializeField] private InputHandler inputHandler;
        [SerializeField] private InputProvider inputProvider;
        [SerializeField] private CinemachineVirtualCamera virtualCamera;
        private CinemachineFramingTransposer _framingTransposer;
    
    #if UNITY_STANDALONE || UNITY_WEBGL
        [SerializeField] private PcCameraSettings pcSettings;
    #else
        [SerializeField] private MobileCameraSettings mobileSettings;
    #endif
    
        private void Start()
        {
    #if UNITY_STANDALONE || UNITY_WEBGL
            moveSpeed = pcSettings.moveSpeed;
            rotateSpeed = pcSettings.rotateSpeed;
            cameraZoomSpeed = pcSettings.cameraZoomSpeed;
            edgeScrollingSpeed = pcSettings.edgeScrollingSpeed;
    #else
            moveSpeed = mobileSettings.moveSpeed;
            rotateSpeed = mobileSettings.rotateSpeed;
            cameraZoomSpeed = mobileSettings.cameraZoomSpeed;
            edgeScrollingSpeed = mobileSettings.edgeScrollingSpeed;
    #endif
    
            // Остальной код старта...
        }
    
        private void Update()
        {
            // Процессы для мобильных и ПК общие
            ProcessRotate();
            ProcessDrag();
            ProcessDragPan();
            ProcessZoom();
            HandleEdgeScrolling();
        }
    
        // Остальные методы...
    }
    

    Заключение

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

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