using UnityEngine;
using UnityEngine.UI;
public class MoveCanvasChildToScreenPos:MonoBehaviour{
public CanvasScaler canvasScaler; //Canvas对象的CanvasScaler组件
public RectTransform rectTransform; //需要移动的Canvas子对象的RectTransform组件
private void Update(){
MoveToScreenPos(Input.mousePosition);
}
private void MoveToScreenPos(Vector2 screenPos){
//屏幕分辨率与设计分辨率的缩放因子
float scaleX=Screen.width/canvasScaler.referenceResolution.x;
float scaleY=Screen.height/canvasScaler.referenceResolution.y;
//加权平均值
float averageValue=scaleX*(1-canvasScaler.matchWidthOrHeight)+scaleY*(canvasScaler.matchWidthOrHeight);
screenPos/=averageValue;
screenPos-=rectTransform.sizeDelta*0.5f;//以中心为枢轴
Vector2 offset=screenPos-rectTransform.offsetMin;
rectTransform.offsetMin=screenPos;
rectTransform.offsetMax=rectTransform.offsetMax+offset;
}
}
原文地址:https://www.cnblogs.com/kingBook/p/12581982.html
时间: 2024-10-14 07:56:03