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

unity3d点击屏幕判断是否击中场景中物体

2015-10-27 18:12 537 查看
问题:

现在要做点击屏幕,然后判断是否击中了3d场景中的一个物体.(就像子弹发射出去,打击目标一样)

思路:

一开始我想的是,我点击屏幕,那么拥有点击处的坐标,然后从点击处创建一个gameobject,然后沿着直线发射出去,然后检测是否发生碰撞.

然后我就这样做:

void Update () {
if(Input.GetMouseButtonDown(0))
{
Vector3 vec1 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}

}


此时我进行了调试,发现无论我点击哪里vec1的值都不改变,也不知道原因是什么,百度了一下发现这个:

Hi,

I'm currently experimenting with ScreenToWorldPoint(), and something just doesn't seem to be working right...

Whenever I use this code:
function Update() {

Debug.Log(camera.ScreenToWorldPoint(Input.mousePosition));

}


[/code]

It just shows (0.0 ,125.0, 0.0) all the time in the Debug console, regardless of how much I move the cursor around the screen.

How can I make my code display the actual world coordinates my mouse is currently passing over?

Thanks in advance. :)

回答:

ScreenToWorldPoint receives a Vector3 argument where x and y are the screen coordinates, and z is the distance from the camera. Since Input.mousePosition.z is always 0, what you're getting is the camera position.

The mouse position in the 2D screen corresponds to a line in the 3D world passing through the camera center and the mouse pointer, thus you must somehow select which point in this line you're interested in - that's why you must pass the distance from the camera
in z.

If you try something like this:
function Update() {

var mousePos = Input.mousePosition;

mousePos.z = 10; // select distance = 10 units from the camera

Debug.Log(camera.ScreenToWorldPoint(mousePos));

}


[/code]

you will get the world point at 10 units from the camera.

翻译一下:

ScreenToWorldPoint 接收一个Vector3 参数,其中x和y是屏幕的坐标,z是与摄像机的距离。如果 Input.mousePosition.z 为0,那么这个函数的返回值将一直是摄像机的位置.

我们点击屏幕的点和摄像机的位置构成一条从摄像机开始发射的射线(这条射线穿透了整个视景体,即:近剪裁平面和远剪裁平面构成的平截头体),从这条射线可以得到一个射线方程,其中的变量就是z值,所以我们只要指定了z值,那么我们就可以得到x和y的坐标。这样就得到了世界坐标空间下的坐标点。

最终的处理办法:

void Update () {
if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray))
{
Debug.Log("okok");
}
}

}


产生一条射线(从摄像机开始,沿着我们点击的点发射出去),然后Raycast 会检测这个射线是否碰撞到物体,如果碰撞返回true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: