Unity UGUI获取鼠标在屏幕的准确点击位置

想要获取鼠标在屏幕的准确点击位置,千万不要胡乱写,什么转化坐标系,什么Ray射线检测都是浮云。html

1,转化坐标系只是相对而言,并不能准确实现当前鼠标点击在屏幕的位置;ui

2,Ray检测,hit是须要碰撞的,没碰撞,获取的是什么??(0,0,0)。this

因此,请看以下正解。spa

第一种:orm

我用坐标系转化时发现值并无什么变化,网上乱七八糟的都有。htm

其实很简单,Input.mousePosition自己就是屏幕坐标(二维),blog

不能直接使用是由于,屏幕空间以像素定义。屏幕的左下为(0,0);右上是(pixelWidth,pixelHeight),get

或者说以屏幕的左下角为(0,0)点,右上角为(Screen.width,Screen.height)it

而屏幕的基准点在屏幕中心(Screen.width/2,Screen.height/2),须要减掉二分之一坐标值,也就是减去二分之一屏幕的宽、高。io

将基准点放置屏幕的左下角,即基准点为(0,0).

此时m_panel的屏幕坐标就对应到tranPos的x、y值。

Transform(RectTransform)  m_panel;

float X = Input.mousePosition.x - Screen.width / 2f;
float Y = Input.mousePosition.y - Screen.height / 2f;
Vector2 tranPos = new Vector2(X,Y);
m_panel.localPosition = tranPos;

注意:须要考虑m_panel的锚点,举例说明:能够这么说,锚点对应坐标中心点。

第二种:使用 RectTransformUtility.ScreenPointToLocalPointInRectangle 方法。

我这里的UICamera是单独检测UI层的相机,能够是MainCamera,若是没有摄像机(即Canvas   --Overlay),则相机为null。

public Vector2 CurrMousePosition(Transform thisTrans)
{
Vector2 vecMouse;
RectTransform parentRectTrans = thisTrans.parent.GetComponent<RectTransform>();
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTrans, Input.mousePosition, UICamera, out vecMouse);
return vecMouse;
}

 

另,获取鼠标的世界坐标: 鼠标在世界坐标下的位置鼠标位置从屏幕坐标转化为世界坐标

相关文章
相关标签/搜索