给定一个已知的方向和范围,我正在尝试计算从起点到该范围内的矢量的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线从起点到鼠标位置是直接的,红线是计算出的矢量:
我尝试了透视和正交相机,我尝试改变起点,问题是一样的。我不知道如何尝试代码,因为我读过的所有内容都表明它应该可行。
可能是什么问题呢?
目前你的endPos位于矢量距离和方向,但是从0,0,0
开始
相反它应该是
endPos = startPos + (hit.point - startPos).normalized * rangeSquared;
或者为了更好地理解
var distance = rangeSquared;
var direction = (hit.point - startPos).normalized;
endPos = startPos + direction * distance;