光线投射统一跳到错误的位置

Raycasting in unity jumping to a wrong position

我遇到光线投射问题。我想做的就是始终知道我的光标在世界 space 中的位置并且它有效,但前提是光标在移动。当光标不移动时,它会跳到 x 轴和 z 轴下方大约 4 个单位的随机点。

public class CameraMovementRay : MonoBehaviour
{
    public Camera playerCam;
    Ray cursorRay;
    Vector3 playerPos;
    public RaycastHit cursorHit;
    public LayerMask clickPlain;
    public bool cursorHittingFloor;

    // Update is called once per frame
    void Update()
    {
        cursorRay = playerCam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(cursorRay, out cursorHit, 100f, clickPlain))
        {
            print(cursorHit.point);
            Debug.DrawLine(cursorRay.origin, cursorHit.point, Color.red);
            cursorHittingFloor = true;

        }
        else
        {
            Debug.LogError("Not on the grund");
            cursorHittingFloor = false;
        }
    }

那是行不通的,但我确实找到了

`` public class LookAtMouse:MonoBehaviour {

public Camera playerCamera;

Plane movementPlane = new Plane(Vector3.up, 0f);
Vector3 lookPoint;

Ray CursorRay;

// Update is called once per frame
void Update()
{
    CursorRay = playerCamera.ScreenPointToRay(Input.mousePosition);
    float enter = 0.0f;

    movementPlane.Raycast(CursorRay, out enter);
    lookPoint = CursorRay.GetPoint(enter);
    print(lookPoint);
    Debug.DrawLine(CursorRay.origin, lookPoint);

    transform.LookAt(lookPoint);

}

} ``

您是否尝试过使用 Camera.ScreenToWorldPoint 而不是 Camera.ScreenPointToRay?我认为它可能更适合您的目的,因为它采用以像素为单位的 Vector2 (MousePosition) 并将其方便地转换为 World Space Point。我所指的 Unity 文档是:https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

告诉我结果如何