使用AR 基础将屏幕触摸位置转换为AR中的世界位置



我在将触摸位置转换为世界坐标时遇到问题。我希望能够将物体放置在我在平面上单击的位置,但是我在使用 Z 轴时遇到了问题。

我正在使用camera.ScreenToWorldPoint()将 Vector2 触摸位置转换为世界位置,但我似乎无法正确获得 Z 轴。

Vector3 pos = new Vector3(vector2.x, vector2.y);
pos = camera.ViewportToScreenPoint(pos);
Ray ray = camera.ScreenPointToRay(new Vector3(pos.x, pos.y, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))   
{
distance = hit.distance;    
}
pos = new Vector3(pos.x, pos.y, distance);
return camera.ScreenToWorldPoint(pos);

没有必要/首先通过ViewportToScreenPoint转换它是没有意义的。Touch.position已经在像素屏幕空间中。

然后你可以直接将其传递到需要这样一个像素空间位置的ScreenPointToRay

最后,如果您已经有RaycastHit那么通过hit.distance再次重新计算 3D 世界空间位置是没有意义的,而只是直接使用RaycastHit.point

因此,假设vector2等于您在像素空间中的触摸位置,那么它宁愿简单地

var ray = camera.ScreenPointToRay(vector2);
if (Physics.Raycast(ray, out var hit))   
{
var hitPos = hit.point;
// ... whatever you want to do with the hit position   
}

悬而未决的问题是:如果光线没有击中任何东西,应该返回什么?

最新更新