游戏世界中从摄像机到鼠标位置的光线投射

Ger*_*rte 5 c# unity-game-engine raycasting

当鼠标位于门(红色区域)时我想做点什么。我正在尝试投射射线,但射线没有击中门,而且我无法找到它到底击中的位置。另外我怎样才能发出Debug.DrawRay这条射线?

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

if (Physics.Raycast(ray, out hit, Mathf.Infinity)) 
{
    if (hit.collider.tag == "InteractiveDoor")
    {
        doorInteractGameObject.SetActive(true);
    }
    else
    {
        doorInteractGameObject.SetActive(false);
    }
}
Run Code Online (Sandbox Code Playgroud)

统一图像

jki*_*idd 0

您可以将这条射线绘制为:

Debug.DrawRay(ray.origin, ray.direction);
Run Code Online (Sandbox Code Playgroud)

或者

Debug.DrawRay(Camera.main.transform.position, Camera.main.ScreenPointToRay(Input.mousePosition).direction);
Run Code Online (Sandbox Code Playgroud)

一旦您定义了射线,选项 1 会更直接,但如果事实证明该射线的行为与您期望的方式不同,选项 2 将为您提供更多选择。

camera.ScreenPointToRay期望 aVector3Input.mousePosition返回 a Vector2。关于 Vector3 和 Vector2 的 Unity 文档似乎表明您应该能够隐式地将 Vector2 用作 Vector3,并且它将 z 分量填充为 0,但如果显示Debug.DrawRay光线是问题所在,那么您需要附加 0。也许就像是:

Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
Run Code Online (Sandbox Code Playgroud)