首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算网格边缘距离

计算网格边缘距离
EN

Stack Overflow用户
提问于 2017-06-21 20:17:34
回答 1查看 1.1K关注 0票数 3

我的鼠标在屏幕上的位置很容易找到,

代码语言:javascript
复制
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);

现在想象一个立方体。单击此多维数据集的任何地方,都会从单击的边缘通过对象绘制一条线,并在另一端停止。方向,无论是垂直的还是水平的,取决于点击哪一面,四个边之一,或顶部或底部。

一个如何确定距离(从一个网格的边缘到另一个)和方向(垂直或水平)?

有什么想法?

到目前为止,我唯一的想法是使用碰撞检测和使用CollisionEnter作为起点,并以某种方式绘制一条到达网格的另一端的线,并使用CollisionExit来确定目标(或出口)点。然后进行计算,确定进出方法之间的距离。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-21 20:40:29

我唯一能想到的办法就是把光线投射回另一个方向.

代码语言:javascript
复制
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
    //offset the ray, keeping it along the XZ plane of the hit
    Vector3 offsetDirection = -hit.normal;
    offsetDirection.y = 0;
    //offset a long way, minimum thickness of the object
    ray.origin = hit.point  + offsetDirection * 100;
    //point the ray back at the first hit point
    ray.direction = (hit.point - ray.origin).normalized;
    //raycast all, because there might be other objects in the way
    RaycastHit[] hits = Physics.RaycastAll(ray);
    foreach (RaycastHit h in hits)
    {
        if (h.collider == hit.collider)
        {
            h.point; //this is the point you're interested in
        }
    }
}

这会将光线偏移到一个新的位置,从而保留原来命中的相同的XZ坐标,因此产生的端点形成一条与世界/场景Y轴垂直的线。为了做到这一点,我们使用相机的Forward方向(因为我们希望得到一个离视图点更远的点)。如果我们想要得到一个垂直于命中表面的线的点(平行于表面法线),我们可以使用hit.normal创建一个偏移。

您可能希望在两个raycast方法中添加一个层掩码或maxdist参数(因此它检查的内容更少,速度更快),但这取决于您。

原始代码:,它通过对象找到一个“单一”射线的两个端点。

代码语言:javascript
复制
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
    //offset the ray along its own direction by A LOT
    //at a minimum, this would be the maximum thickness of any object we care about,
    //PLUS the distance away from the camera that it is
    ray.origin += ray.direction * 100;
    //reverse the direction of the ray so it points towards the camera
    ray.direction *= -1;
    //raycast all, because there might be other objects in the way
    RaycastHit[] hits = Physics.RaycastAll(ray);
    foreach(RaycastHit h in hits)
    {
        if(h.collider == hit.collider)
        {
            h.point; //this is the point you're interested in
        }
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44685529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档