坐标转换

来源:互联网 发布:灰度共生矩阵 编辑:程序博客网 时间:2024/06/10 08:56

//2D转3D

        public static string curHitTag;

    public static Vector3 pointTo3d(Vector2 position,Camera mcamera,string layerName){
                
        LayerMask mask = 1 << LayerMask.NameToLayer(layerName);
        
        Ray ray = mcamera.ScreenPointToRay(new Vector3 (position.x,position.y,0));
        RaycastHit hit;
        if (Physics.Raycast(rayout hit,800,mask)){
            
            curHitTag = hit.transform.tag;
            
            return hit.point;
        }
        
        curHitTag = null;
        
        return Vector3.zero;
    }

//注:LayerMask实际上是用Int32的32个位来表示每个层级,当这个位为1时表示使用这个层,为0时表示不用这个层



//3D转2D

    public static Vector3 pointTo2d(Vector3 piont){
        //GameObject mainCamera = GameObject.Find("Main Camera");
        Camera camera = Camera.main;
        Vector3    screenPiont = camera.WorldToScreenPoint(piont);
        Vector3    viewportPiont = camera.WorldToViewportPoint(piont);
        
        //Debug.Log(" screenPiont "+ screenPiont +" viewportPiont"+ viewportPiont);

        GameObject  canvas =  GameObject.Find("Canvas");
        CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler>();
        float width  =  canvas.GetComponent<RectTransform>().rect.width;
        float height =  canvas.GetComponent<RectTransform>().rect.height;
        
        float wb = width / Screen.width  ;
        float hb = height / Screen.height  ;
        
        return new Vector3screenPiont.x * wb - width * 0.5f,screenPiont.y * hb - height * 0.5f,0);
    }

//屏幕中心

    public static Vector3 get2DpiontScreenCenter(){
        return new Vector3(Screen.width * .5fScreen.height * .5f0);
    }

//屏幕中心地面坐标
    public static Vector3 get3DpiontScreenCenter(){
        GameObject mainCamera = GameObject.Find("Main Camera");
        Camera camera = mainCamera.GetComponent<Camera> ();
        Ray ray1 = camera.ScreenPointToRay (new Vector3 (Screen.width * .5fScreen.height * .5f0));
        RaycastHit hit1;
        if (Physics.Raycast (ray1out hit1)) {
            return hit1.point;
        }
        
        return new Vector3();
    }

0 0
原创粉丝点击