【问题标题】:Find point at distance along a vector沿向量查找距离处的点
【发布时间】:2019-02-16 22:27:11
【问题描述】:

给定一个已知的方向和范围,我试图计算从起点开始在该范围内沿向量的 3D 位置。

为此,我基本上遵循 Unity 手册以及有关此主题的各种其他问题中提供的解决方案:

按照你的方向,规范化它并乘以所需 距离。

这对我不起作用,但我不知道出了什么问题。这是我的代码,应该从起点向鼠标光标位置画一条线,在距起点的给定距离处结束:

IEnumerator DrawLineToMouse(float range)
{   
    RayCastHit hit;
    Vector3 endPos;
    float rangeSquared = Mathf.Sqrt(range);

    while (Input.GetButton("Fire1"))
    {
        if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 2000))
        {
            endPos = (hit.point - startPos).normalized * rangeSquared; // startPos is the starting point of the line to be drawn  
            Debug.DrawLine(startPos, hit.point, Color.green, Time.deltaTime);
            Debug.DrawLine(startPos, endPos, Color.red, Time.deltaTime);   
        } 

        yield return null;
    }
}

由于某种原因,方向似乎偏离了。在这张图中,绿色的Debug.Draw线是从起点直接到鼠标位置,红线是到计算的向量:

我尝试过透视相机和正交相机,并且尝试过改变起点,问题是一样的。我不知道该尝试什么代码,因为我读过的所有内容都表明它应该可以工作。

可能是什么问题?

【问题讨论】:

    标签: unity3d 3d


    【解决方案1】:

    目前您的 endPos 位于矢量距离和方向,但从 0,0,0 开始

    相反,它应该是

    endPos = startPos + (hit.point - startPos).normalized * rangeSquared;
    

    或者为了更好的理解

    var distance = rangeSquared;
    var direction = (hit.point - startPos).normalized;
    
    endPos = startPos + direction * distance;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 2022-08-15
      相关资源
      最近更新 更多