0

Имеется 2D игра казуальная мобилка, в которой мышкой можно двигать объекты. Камерой двигать тоже можно. Конечно, имеются UI-элементы(кнопки).

Проблема

Если за UI-кнопкой находится объект, который можно двигать, и если нажать на эту кнопку, то захватится объект за ним. Как сделать так, чтобы нельзя было двигать объект, если он находится за UI-элементом?

Мои попытки

В начале пытался использовать интерфейсы разные на нажатие кнопки и отжатие кнопки, чтобы выключать компонент, который отвечает за перетаскивание объекта при нажатии, например, кнопки мыши, но с UI интерфейсы работают некорректно, как например, с обычными gameObject объектами. Затем, в голову пришло добавить коллизию на места где кнопки, то столкнулся с тем, что не могу понять как поставить коллизию в сцене туда где отображается UI-кнопки.

Может есть что нибудь на подобии якорей для Canvas,но для gameObject?

Ссылка на видос проблемы - https://youtu.be/FJpuTfTbBLE

Скрипт на движение камерой

 if (Input.touchCount == 1 && _dragContoller.CanMoveCamera && _canMoveFromSlider)
    {
        _touch = Input.GetTouch(0);          

        if (_touch.phase == TouchPhase.Moved)
        {
            Vector3 movePos = new Vector3(
                transform.position.x + _touch.deltaPosition.x * _speed * -1 * Time.deltaTime,
                transform.position.y + _touch.deltaPosition.y * _speed * -1 * Time.deltaTime,
                transform.position.z);
            Vector3 distance = movePos - transform.position;
            transform.position += distance;
        }
    }     
    transform.position = new Vector3(
 Mathf.Clamp(transform.position.x, _leftLimit, _rightLimit),  

Mathf.Clamp(transform.position.y, _bottomLimit, _topLimit),
  transform.localPosition.z);

Скрипт переноса объектов

 private bool _isDragActive = false;
private Vector2 _screenPosition;
private Vector3 _worldPosition;
private Draggable _lastDragged;
[SerializeField] private bool _canMoveCamera;
[SerializeField] private CustomSlider _slider;
private DragController _selfController;
public bool CanMoveCamera => _canMoveCamera;

private void Awake()
{
    DragController[] controllers = FindObjectsOfType<DragController>();
    if (controllers.Length > 1)
    {
        Destroy(gameObject);
    }
    _selfController = this;
}
private void Start()
{
    _canMoveCamera = true;
    _slider.e_canMoveFromSlider += (bool x) =>{ _selfController.enabled = x; Drop();};
}


private void Update()
{
    if (_isDragActive && (Input.GetMouseButtonUp(0) || (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Ended)))
    {//Если  перестивание активно и отпущено нажатие,то сброс
        Drop();
        return;
    }
    else if (Input.GetMouseButton(0))//fix = раньше было просто if без else
    {
        Vector3 mousePos = Input.mousePosition;
        _screenPosition = new Vector2(mousePos.x, mousePos.y);
    }
    else if (Input.touchCount > 0)
    {
        _screenPosition = Input.GetTouch(0).position;
    }
    else
    {
        return;
    }
    _worldPosition = Camera.main.ScreenToWorldPoint(_screenPosition);
    if (_isDragActive)
    {
        Drag();
    }
    else
    {
        RaycastHit2D hit = Physics2D.Raycast(_worldPosition, Vector2.zero);
        if (hit.collider != null)
        {
            Draggable draggable = hit.transform.gameObject.GetComponent<Draggable>();
            if (draggable != null)
            {
                _lastDragged = draggable;
                InitDrag();
            }
        }
    }
}
private void InitDrag()
{
    _isDragActive = true;
    _canMoveCamera = false;
}
private void Drag()
{
    _lastDragged.transform.position = new Vector2(_worldPosition.x, _worldPosition.y);
} 

 public   void Drop()
    {
        _isDragActive = false;
        _canMoveCamera = true;
    }
}

1 ответ 1

0

Если не было взаимодействие с каким либо UI у которого RaycastTarget ☑

using UnityEngine.EventSystems;

if (EventSystem.current.IsPointerOverGameObject() == false) 
{
    //...
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.