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的位置,我們也就将螢幕坐标轉換為了世界坐标。
官網文檔中的說法:
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);
}
}
部落客測試:
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;
}
}