zoukankan      html  css  js  c++  java
  • Unity UGUI获取鼠标在屏幕的准确点击位置

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

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

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

    所以,请看如下正解。

    第一种:

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

    其实很简单,Input.mousePosition本身就是屏幕坐标(二维),

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

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

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

    将基准点放置屏幕的左下角,即基准点为(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;
    }

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

  • 相关阅读:
    ubuntu與win7雙系統引導的默認系統問題
    Mac正确删除应用程序的方法
    latex链接外部文件
    ubuntu安装sunjava6
    String.Index 和 String.Split的用法例子
    关于数组传递以及ref,out的例子
    通过XElement查询XML的几种方法
    递归的基本例子
    frame与iframe的区别
    C#数组的用法,out传递值的用法
  • 原文地址:https://www.cnblogs.com/yanghui0702/p/yanghui20180521.html
Copyright © 2011-2022 走看看