【问题标题】:Mouse based aiming Unity3d基于鼠标的瞄准 Unity3d
【发布时间】:2015-06-23 17:44:15
【问题描述】:

我正在制作炮弹射击游戏。这是我计算瞄准方向的简短代码。

            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角度并相应地抛出。

【问题讨论】:

    标签: c# vector unity3d physics game-physics


    【解决方案1】:

    在这种情况下使用 Camera.ScreenToWorldPoint 是错误的。

    您应该对飞机使用光线投射。这是一个没有不必要数学的演示:

    Raycasting 为您提供了优势,您不必猜测用户点击的“深度”有多深(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

    【讨论】:

    • 干得好!但是每次我想计算鼠标位置时都需要创建一个平面吗?是的,您可以为所有人上传一个可播放的演示。
    • 对不起,没有注意到你关于飞机的问题:这不是必需的,但它很便宜,你不应该打扰它。它只是一个数学结构,并不比向量复杂多少。另外,如果每帧都重新计算,那么您可以轻松移动飞机。
    • 对我来说,这总是返回异常。
    • @personthehuman,你确定鼠标指针在飞机上吗?也许您必须移动带有此脚本的相机或游戏对象?如果不确定如何使用脚本,请查看演示项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2011-07-21
    相关资源
    最近更新 更多