世界坐标转画布坐标

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainTest : MonoBehaviour {

    public RectTransform rectCanvas; //画布节点
    public Camera worldCamera; //场景相机
    public Camera uiCamera; //画布相机

    public Transform cube; //测试用的场景对象 

    public UnityEngine.UI.Image image; //测试用UI图标

    private GUIStyle style;

    void Start()
    {
        style = new GUIStyle();
        style.fontSize = 24;
        style.normal.background = new Texture2D(300,100);
        style.normal.textColor = new Color(0.3f,0.3f,0.5f,1f); 
    }

    void OnGUI()
    { 
        //计算场景坐标到画布坐标
        if (GUILayout.Button("世界坐标转为画布坐标", style))
        {
            Vector2 canvasSize = rectCanvas.sizeDelta;
            Vector3 viewPortPos3d = worldCamera.WorldToViewportPoint(cube.position);
            Vector2 viewPortRelative = new Vector2(viewPortPos3d.x - 0.5f, viewPortPos3d.y - 0.5f);
            Vector2 cubeScreenPos = new Vector2(viewPortRelative.x * canvasSize.x, viewPortRelative.y * canvasSize.y);

            Debug.LogError("ScrrenSize="+canvasSize
                +",cube.position="+cube.position
                +",viewPortPos3d="+viewPortPos3d+",screenPos="+cubeScreenPos+",newPos="+viewPortRelative);


            image.rectTransform.anchoredPosition = cubeScreenPos;
        }

        GUILayout.Label("\n");

        if (GUILayout.Button("随机修改cube坐标", style))
        { 
            float rate = 5f;
            Vector3 newPos = cube.position + new Vector3(UnityEngine.Random.Range(-rate, rate), UnityEngine.Random.Range(-rate, rate), 0);
            cube.position = newPos;
        }
    }    
}
--------------------- 
作者:Stephanie_1 
来源:CSDN 
原文:https://blog.csdn.net/Stephanie_1/article/details/78132070 
版权声明:本文为博主原创文章,转载请附上博文链接!

效果图

猜你喜欢

转载自blog.csdn.net/qq_32354205/article/details/83346636