您的位置:首页 > 移动开发 > Unity3D

unity3d鼠标点击,获取世界坐标

2014-07-04 02:38 246 查看
unity中有关于鼠标位置的函数,Input.mousePosition。但不得不说,这个函数不到位,可以用一个print函数输出一下这个坐标会发现,只有X,Y值在改变,Z值没有发生变化,并且在屏幕的左下角固定为(0,0,0),查看文档后发现,文档上是这么写的。

The current mouse position in pixel coordinates. (Read Only)

当前所在像素坐标的鼠标位置(只读)。

The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width,Screen.height).

屏幕或窗口的左下角是坐标系的(0,0)坐标。右上角的坐标是(屏幕宽度值,屏幕高度值)。

即我们得到的坐标是其实是摄像机显示画面的坐标,就是我们屏幕的坐标,我直接就纠结了,这怎么办?

在近1个小时的文档查看过程中还是没有找到有关鼠标位置的函数,但是偶然间看到了一个射线的方法

原来是用这种方式做的啊!!

找到目标后开始研究这个射线函数,霍霍,ScreenPointToRay这个太到位了!

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)。

这就明白了,函数给我们的是一条射线,起点是摄像机,且射线过屏幕上的一点,屏幕上的点不就是mousePosition吗,解决了!

c#

if (Input.GetMouseButton(0)) {

//Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

Ray ray = camera.ScreenPointToRay(Input.mousePosition);

上面注释掉的函数:当你的脚本没有绑在mainCamera上时,又想用MainCamera做原点是使用。

接下来我们来试一下效果到底行不行,继续写void Update()

//这段代码是我照文档改的,自己似懂非懂,请各位读者指点

RaycastHit hit;//

if(Physics.Raycast(ray, out hit))//函数是对射线碰撞的检测,这个out是什么意思?

{

Point = hit.point;//得到碰撞点的坐标

print (Point);//输出一下

print("I'm looking at " + hit.transform.name);//输出碰到的物体名字

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: