实现功能:ui物体跟随鼠标移动,当ui超出屏幕的时候,自动适配到屏幕内。
在这里插入代码片
//ui显示的方位
public enum Orientation
{
LeftDown = 0,
LeftUp,
LeftCenter,
RightUp,
RigthDown,
RightCenter,
CenterUp,
CenterDown,
Center
}
public class ScreenLimit : MonoBehaviour
{
[Tooltip("物体方位")]
public Orientation m_ori;
[Tooltip("限制在屏幕内的物体")]
public RectTransform target;
[Tooltip("出现的位置相对于手指点击位置的偏移量")]
public float m_posOffset = 55f;
public CanvasScaler canvasScaler;
private bool _isbuttonDown = false;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
_isbuttonDown = true;
}
else if (Input.GetMouseButtonUp(0))
{
_isbuttonDown = false;
}
if (_isbuttonDown)
{
SetUIPos();
}
}
/// <summary>
/// 根据位置信息,设置不同方位的偏移量
/// </summary>
public void SetUIPos()
{
Vector2 curInputPos = Input.mousePosition;
float x = curInputPos.x;
float y = curInputPos.y;
float w = Mathf.Abs(target.rect.x) * GetScaleFactor<