canvas坐标转换屏幕坐标_Unity 屏幕坐标到UGUI RectTransform本地坐标的转换

本文介绍了如何在Unity中使用RectTransformUtility.ScreenPointToLocalPointInRectangle方法将屏幕坐标转换为RectTransform本地坐标。提供了相关代码示例,帮助理解转换过程,并提到了可以从EventSystem获取基于屏幕坐标的点击位置。
摘要由CSDN通过智能技术生成

public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint);

rect: 对应的 RectTransform 的引用

screenPoint: 位置,基于屏幕坐标系

cam: 相机的引用,如果Canvas的Render Mode 为 Screen Space - Camera 模式,则需要填入 Render Camera 对应的引用

localPoint: rect 本地坐标系下的坐标(原点(0,0)位置受Anchor的影响)

参考:

https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html

using UnityEngine;

using UnityEngine.UI;

using System.Collections;

using UnityEngine.EventSystems;

public class GlobalTest : MonoBehaviour

{

public Canvas canvas;

Text uiText;

RectTransform canvasRect;

RectTransform textRect;

void Start()

{

uiText = canvas.GetComponentInChildren();

canvasRect = canvas.GetComponent();

textRect = uiText.GetComponent();

Debug.Log(textRect.anchoredPosition);

}

void Update()

{

if (Input.GetMouseButtonUp(0))

{

Vector2 outVec;

if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect,Input.mousePosition,null,out outVec))

{

Debug.Log("Setting anchored positiont to: " + outVec);

textRect.anchoredPosition = outVec;

}

}

}

}

参考:

https://forum.unity.com/threads/issues-with-recttransformutility-screenpointtolocalpointinrectangle.437246/

再说一句

也可以从UGUI的EventSystem中获得鼠标基于屏幕坐标系的点击位置

public void OnPointerDown(PointerEventData pointerEventData)

{

//Output the name of the GameObject that is being clicked

Debug.Log(name + "Game Object Click in Progress");

}

标签:UnityEngine,outVec,RectTransform,Unity,坐标,using,textRect,public

来源: https://www.cnblogs.com/dj1232090/p/11162516.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值