Задать вопрос
  • Как запретить персонажу (2D) выход за границы камеры, с учётом высоты статус бара?

    @Lalka-Game-Studio Автор вопроса
    Используя комментарий пользователя DrRen7, я решил задачу. Полный рабочий скрипт выглядит вот так:

    using UnityEngine;
    
    public class PlayerController : MonoBehaviour
    {
        [SerializeField] GameObject canvasObject;
        [SerializeField] GameObject statusBarObject;
    
        private float speed = 10f;
    
        private Camera mainCamera;
        private Vector2 minBounds;
        private Vector2 maxBounds;
    
        private float halfWidth;
        private float halfHeight;
    
        private float statusBarRealHeight;
    
        void Start()
        {
            mainCamera = Camera.main;
    
            // Получаем размеры спрайта персонажа
            SpriteRenderer sr = GetComponent<SpriteRenderer>();
            halfWidth = sr.bounds.extents.x;
            halfHeight = sr.bounds.extents.y;
        }
    
        void Update()
        {
            Movement();
        }
    
        void Movement()
        {
            UpdateBounds();
            CalcStatusBarRealHeight();
    
            float horDirection = Input.GetAxis("Horizontal");
            float vertDirection = Input.GetAxis("Vertical");
    
            Vector3 newPosition = transform.position + speed * Time.deltaTime * new Vector3(horDirection, vertDirection, 0);
    
            // Ограничиваем позицию по X и Y с учётом размеров персонажа и границ камеры, а также высоты статус бара
            newPosition.x = Mathf.Clamp(newPosition.x, minBounds.x + halfWidth, maxBounds.x - halfWidth);
            newPosition.y = Mathf.Clamp(newPosition.y, minBounds.y + halfHeight, maxBounds.y - halfHeight - statusBarRealHeight);
    
            transform.position = newPosition;
        }
    
        void UpdateBounds()
        {
            // Получаем границы камеры в мировых координатах
            Vector3 bottomLeft = mainCamera.ViewportToWorldPoint(new Vector3(0, 0, mainCamera.nearClipPlane));
            Vector3 topRight = mainCamera.ViewportToWorldPoint(new Vector3(1, 1, mainCamera.nearClipPlane));
    
            minBounds = bottomLeft;
            maxBounds = topRight;
        }
    
        // Вычисляем высоту статус бара
        void CalcStatusBarRealHeight()
        {
            float canvasScale = canvasObject.GetComponent<RectTransform>().localScale.y;
            float absoluteHeight = statusBarObject.GetComponent<RectTransform>().sizeDelta.y;
            statusBarRealHeight = absoluteHeight * canvasScale;
        }
    }
    Ответ написан
    Комментировать