我能想到的唯一方法就是向另一个方向投射光线......
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
代替。
您可能希望将 layermask 或 maxdist 参数放入两个 raycast 方法中(因此它检查的东西更少并且更快),但这取决于您。
原始代码:找到通过对象投射的“单一”射线的两个端点。
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
}
}
}