基于鼠标的瞄准 Unity3d

3

我正在制作一个炮弹射手游戏。以下是一段简短的代码,我在其中计算瞄准方向。

            Vector3 mousePos = Input.mousePosition;
            mousePos.z = thisTransform.position.z - camTransform.position.z;
            mousePos = mainCamera.ScreenToWorldPoint (mousePos);

            Vector3 force = mousePos - thisTransform.position;
            force.z = force.magnitude;

这段代码在球和相机都位于(0,0,0)的情况下有效,但当角度发生变化时,我无法朝正确的方向投球。

假设球和相机都向右侧45度看,同样的代码就失效了。

当前的代码假定两者都位于(0,0,0)。因此,在上述情况下,投掷方向总是错误的。

我希望能够将球投向任何方向,但假定它为0角度并相应地投掷。

1个回答

7
在此情况下使用“Camera.ScreenToWorldPoint”是错误的。
您应该使用对平面进行射线投射。以下是一个没有不必要数学内容的演示:
射线投射使您具有优势,您无需猜测用户单击的“深度”(即“z”坐标)。
以下是上述内容的简单实现:
/// <summary>
/// Gets the 3D position of where the mouse cursor is pointing on a 3D plane that is
/// on the axis of front/back and up/down of this transform.
/// Throws an UnityException when the mouse is not pointing towards the plane.
/// </summary>
/// <returns>The 3d mouse position</returns>
Vector3 GetMousePositionInPlaneOfLauncher () {
    Plane p = new Plane(transform.right, transform.position);
    Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
    float d;
    if(p.Raycast(r, out d)) {
        Vector3 v = r.GetPoint(d);
        return v;
    }

    throw new UnityException("Mouse position ray not intersecting launcher plane");
}

演示: https://github.com/chanibal/Very-Generic-Missle-Command

干得好!但是每次想要计算鼠标位置都需要创建一个平面吗?是的,请上传一个可玩的演示给大家。 - Krishna Kumar
抱歉,没有注意到你关于平面的问题:它并不是必需的,但价格如此便宜,你不应该为此烦恼。它只是一个数学构造,比向量复杂度不高。而且如果每帧重新计算一次,那么你可以轻松地移动平面。 - Krzysztof Bociurko
对我来说,这总是返回一个异常。 - person the human
@personthehuman,你确定鼠标指针在平面上吗?也许你需要移动相机或拥有此脚本附加的GameObject?如果不确定如何使用脚本,请查看演示项目。 - Krzysztof Bociurko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接