當我實作滑鼠可以拖動視窗時、或者某個時刻在不確定的位置彈出tips面板,有時候,該面板的位置可能會有點偏,視窗視野顯示不全,面板內容超出視窗顯示了,我們可以寫一個簡單的類,專門用來讓ui面板保持在狂口內顯示的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIKeepInScreen : MonoBehaviour
{
/// <summary>
/// 視窗RectTransform
/// </summary>
public RectTransform rect;
void Update()
{
// 世界空間
Vector2 minworld = transform.TransformPoint(rect.rect.min);
Vector2 maxworld = transform.TransformPoint(rect.rect.max);
Vector2 sizeworld = maxworld - minworld;
// 保持最小的位置在螢屏邊界-大小
maxworld = new Vector2(Screen.width, Screen.height) - sizeworld;
// 保持位置在(0,0)和maxworld之間
float y = Mathf.Clamp(minworld.y, 0, maxworld.y);
float x = Mathf.Clamp(minworld.x, 0, maxworld.x);
// set new position to xy(=local) + offset(=world)設定新位置為xy(=本地)+偏移量(=世界)
Vector2 offset = (Vector2)transform.position - minworld;
transform.position = new Vector2(x, y) + offset;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/168382.html
標籤:其他
下一篇:Java系列——五子棋的實作
