Camera.ScreenToWorldPoint方法介绍

Camera.ScreenToWorldPoint方法介绍

Camera.ScreenToWorldPoint是Unity中的一个方法,用于将屏幕坐标系中的点转换为世界坐标系中的点。这个方法通常用于将鼠标点击的位置(屏幕坐标系)转换为游戏世界中的位置(世界坐标系)。

Camera.ScreenToWorldPoint方法参数

Camera.ScreenToWorldPoint方法有一个参数,即一个二维向量。这个向量代表了屏幕坐标系中的一个点的位置。该向量的x和y值通常可以通过Input.mousePosition获取。

Camera.ScreenToWorldPoint方法举例子

举例1:将鼠标点击位置转换为世界坐标系中的位置

void Update()
{
    
    
    if (Input.GetMouseButtonDown(0))
    {
    
    
        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = Camera.main.nearClipPlane;

        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePosition);

        Debug.Log("Mouse position in world space: " + worldPosition);
    }
}

在这个例子中,当鼠标左键被按下时,我们获取当前鼠标的位置,并将其z值设置为摄像机的近裁剪面位置,然后使用Camera.ScreenToWorldPoint方法将屏幕上的点转换为世界坐标系中的点。最后,我们使用Debug.Log来输出转换后的世界坐标系中的位置。

举例2:将UI元素的位置转换为世界坐标系中的位置

void Update()
{
    
    
    if (Input.GetMouseButtonDown(0))
    {
    
    
        Vector3 uiPosition = uiElement.transform.position;
        Vector3 screenPosition = Camera.main.WorldToScreenPoint(uiPosition);
        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);

        Debug.Log("UI element position in world space: " + worldPosition);
    }
}

在这个例子中,我们获取了一个UI元素的位置(在Canvas中),然后使用Camera.WorldToScreenPoint方法将其转换为屏幕坐标系中的点。接下来,我们使用Camera.ScreenToWorldPoint方法将该点转换为世界坐标系中的点。最后,我们使用Debug.Log来输出转换后的世界坐标系中的位置。

举例3:将相机的位置转换为世界坐标系中的位置

void Start()
{
    
    
    Vector3 cameraPosition = Camera.main.transform.position;
    Vector3 worldPosition = Camera.main.ScreenToWorldPoint(cameraPosition);

    Debug.Log("Camera position in world space: " + worldPosition);
}

在这个例子中,我们获取了相机的位置,并直接将其作为参数传递给Camera.ScreenToWorldPoint方法。由于相机的位置是在世界坐标系中的,所以我们可以直接得到相机在世界坐标系中的位置。最后,我们使用Debug.Log来输出转换后的世界坐标系中的位置。

猜你喜欢

转载自blog.csdn.net/qq_20179331/article/details/130894299