Camera.ScreenPointToRay 屏幕位置转射线

function ScreenPointToRay (position : Vector3) : Ray

Description描述

Returns a ray going from camera through a screen point.

返回一条射线从摄像机通过一个屏幕点。

Resulting ray is in world space, starting on the near plane of the camera and going through position's (x,y) pixel coordinates on the screen (position.z is ignored).

产生的射线是在世界空间中,从相机的近裁剪面开始并穿过屏幕position(x,y)像素坐标(position.z被忽略)。

Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight).

屏幕空间以像素定义。屏幕的左下为(0,0);右上是(pixelWidth,pixelHeight)。

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	void Update() {
		Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
		RaycastHit hit;
		if (Physics.Raycast(ray, ref hit))
			print("I'm looking at " + hit.transform.name);
		else
			print("I'm looking at nothing!");
	}
}
// Prints the name of the object camera is directly looking at
//打印相机直接看到物体名称

function Update () {
	// Get the ray going through the center of the screen
	//获取穿过屏幕中心的射线
	var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
	// Do a raycast
	//投射
	var hit : RaycastHit;
	if (Physics.Raycast (ray, hit))
	print ("I'm looking at " + hit.transform.name);
	else
	print ("I'm looking at nothing!");
}
最后修改:2011年3月7日 Monday 11:38

本脚本参考基于Unity 3.4.1f5

英文部分版权属©Unity公司所有,中文部分© Unity圣典 版权所有,未经许可,严禁转载 。