【问题标题】:How to get sprite following mouse position when camera is rotated 30 degree on X axys on UNITY3D?当相机在 UNITY3D 的 X 轴上旋转 30 度时,如何让精灵跟随鼠标位置?
【发布时间】:2019-10-16 19:56:11
【问题描述】:

我试图让一个精灵跟随我的鼠标位置,我的相机在 x 轴上旋转 30,如果相机的旋转为 0,0,0 但不是在 30,0,0,这工作正常,我如何必须计算这个吗?我尝试减去 x 位置但没有成功,这是我的代码:

这是附加在我要跟随鼠标的对象上

private void FixedUpdate()
{
    Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition);
    transform.position = new Vector3(pos.x, pos.y, transform.position.z);
}

编辑:我的相机也是正交的而不是透视的

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    ScreenToWorldPoint 在这里并不合适,因为您还不知道将精灵远离相机的适当距离。相反,请考虑使用光线投射(代数上,使用Plane)来确定放置精灵的位置。

    在精灵的位置创建一个 XY 平面:

    Plane spritePlane = new Plane(Vector3.forward, transform.position);
    

    使用Camera.ScreenPointToRay从光标位置创建射线:

    Ray cursorRay = cam.ScreenPointToRay(Input.mousePosition);
    

    找到该射线与平面相交的位置并将精灵放置在那里:

    float rayDist;
    spritePlane.Raycast(cursorRay, out rayDist);
    transform.position = cursorRay.GetPoint(rayDist);
    

    总共:

    private void FixedUpdate()
    {
        Plane spritePlane = new Plane(Vector3.forward, transform.position);
        Ray cursorRay = cam.ScreenPointToRay(Input.mousePosition);
    
        float rayDist;
        spritePlane.Raycast(cursorRay, out rayDist);
    
        transform.position = cursorRay.GetPoint(rayDist);
    }
    

    【讨论】:

    • 你应该考虑不要把它放在FixedUpdate,而是放在UpdateLateUpdate(如果例如相机可以移动)
    • 但是如果我的相机是正交的,我还需要使用光线投射吗?我不能以某种方式计算精灵的距离,因为我的相机在 Z 上而不是在 X,Y 上
    • @Sociopath 如果你想问“使用Raycast 效率低吗?”,答案是否定的,因为Plane.Raycast only does a line or two of vector math。您可以自己实现它,但当Plane.Raycast 已经存在时,这并不是必需的。
    • 谢谢我学到了很多,而且你的代码就像一个魅力,顺便说一句,在 ScreenPointToRay 它的 cam.ScreenPointToRay (主摄像头)
    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2012-01-03
    相关资源
    最近更新 更多