unity中Camera.ScreenToWorldPoint

Camera.ScreenToWorldPoint
Vector3 ScreenToWorldPoint(Vector3 position);

将屏幕坐标转换为世界坐标。

如何转换?假如给定一个所谓的屏幕坐标(x,y,z),如何将其转换为世界坐标?

首先,我们要理解摄像机是如何渲染物体的:

摄像机对游戏世界的渲染范围是一个平截头体,渲染边界是一个矩形,用与near clippingplane或者far clippingplane平行的平面截取这个平截头体,可以获得无数个平行的矩形面,也就是我们看到的屏幕矩形。离摄像机越远,矩形越大,离摄像机越近,矩形越小。所以,同样大小的物体,随着离摄像机越来越远,相对于对应屏幕矩形就越来越小,所看起来就越来越小。

在屏幕上,某个像素点相对于屏幕矩形的位置,可以对应于游戏世界中的点相对于某个截面的位置,关键在于这个点在哪个截面上,也就是说,关键在于这个截面离摄像机有多远!

 

在ScreenToWorldPoint这个方法中,参数是一个三维坐标,而实际上,屏幕坐标只能是二维坐标。参数中的z坐标的作用就是:用来表示上述平面离摄像机的距离。

也就是说,给定一个坐标(X,Y,Z),

首先截取一个垂直于摄像机Z轴的,距离为Z的平面P,这样不管X,Y怎么变化,返回的点都只能在这个平面上;

然后,X,Y表示像素坐标,根据(X,Y)相对于屏幕的位置,得到游戏世界中的点相对于截面P的位置,我们也就将屏幕坐标转换为了世界坐标。

 

官网文档中的说法:

Camera.ScreenToWorldPoint
 
 Vector3 ScreenToWorldPoint(Vector3 position);
Description
 Transforms position from screen space into world space.
  
  Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.

 

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    void OnDrawGizmosSelected() {
        Vector3 p = camera.ScreenToWorldPoint(new Vector3(100, 100, camera.nearClipPlane));
        Gizmos.color = Color.yellow;
        Gizmos.DrawSphere(p, 0.1F);
    }
}

  

博主测试:

在屏幕上创建一个cube,摄像机从上往下照 ,让cube跟随鼠标移动

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

public class MainCameraScript : MonoBehaviour {

    public  int pixelWidth;
    public int pixelHeight;

    public Vector3 mousePosition;

    public Vector3 worldPosition;

    public GameObject cube;

    // Use this for initialization
    void Start () {


      

    }
	
	// Update is called once per frame
	void Update () {

        pixelWidth = this.GetComponent<Camera>().pixelWidth;

        pixelHeight = this.GetComponent<Camera>().pixelHeight;

        mousePosition = Input.mousePosition;

        mousePosition.z = this.GetComponent<Camera>().farClipPlane;

        worldPosition = this.GetComponent<Camera>().ScreenToWorldPoint(mousePosition);

        cube.GetComponent<Transform>().position = worldPosition;


    }
}

  

 

posted on 2018-10-22 23:54  jiahuafu  阅读(3252)  评论(0编辑  收藏  举报

导航