kingBook

导航

unity移动Canvas的子对象到屏幕坐标

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;
	}
}

posted on 2020-04-13 11:28  kingBook  阅读(767)  评论(0编辑  收藏  举报