【问题标题】:Unity - Math question about Vector calculationUnity - 关于向量计算的数学问题
【发布时间】:2021-04-02 07:23:05
【问题描述】:

我正在寻找以下问题的数学公式(在 3 维空间中,因此它大约是 3 维向量)。我在 Unity 中编程 - GameEngine (C#)

在第一张图片中,您可以看到我当前的结果。我创建了 2 个向量(红色球体)并自动生成一个锚点(图中的绿色)。这个锚点总是在第二个向量“后面”生成(在一条直线上)。这两个向量始终是当前向量和前一个向量。 我当前的计算(第一张图片)如下所示:

 Vector3 direction = newVector.position - previousVector.position;
 Vector3 newAnchor.position = newVector.position + direction;

我需要的是第二张图片。我希望始终在第二个向量的“右侧”90 度生成锚点(绿色)(相对于两个向量的方向)。但是,我无法为此进行数学计算。

希望我可以用图片来描述我试图实现的目标。

第一张图片:

第二张图:

【问题讨论】:

  • 所以你想将direction 旋转90 度,然后再添加到newVector.position
  • 是的,我认为这可能是一个解决方案。 2. 围绕矢量旋转
  • 你可以试试direction = Quaternion.Euler(0, 0, 90) * (-direction);然后将方向添加到 newVector.position。但是结果会被方向向量的大小抵消。然后,您可以更改其大小,因为您似乎总是希望锚点的长度相同。顺便说一句,如果 XZ 平面上的点那么你必须使用 Quaternion.Euler (0, 90, 0)。

标签: c# unity3d math vector calculation


【解决方案1】:

二维

为了将矢量旋转 90 度,您只需切换 x 和 y 分量并否定其中一个。可以做扩展方法,直接在vector上调用vector.Left() & vector.Right()

public static class VectorX
{
    public static Vector2 Left(this Vector2 v)
    {
        return new Vector2(-v.y, v.x);
    }

    public static Vector2 Right(this Vector2 v)
    {
        return new Vector2(v.y, -v.x);
    }
}

3D

您可以使用Cross Product,它返回一个与其他两个垂直的向量。

var right = Vector3.Cross(forward, up).normalized;

因此,如果您给出一个点的前向矢量和向上矢量,您将收到一个指向右侧的矢量。如果你想让它指向左边,你可以否定它。

【讨论】:

  • 只有在需要将其旋转 90° 时才有效,但 OP 希望矢量旋转垂直于前一个矢量
  • @nka_Zz 很好,我已经更新了答案。
【解决方案2】:

嘿,我猜你想基本上找到一个与它前面的向量方向相同的粒子,然后让它在单位距离处垂直于向量。

我建议使用所需的或胶囊投射的光线投射到该向量。

这是我建议的伪代码

        public void FixedUpdate()
        {
//https://docs.unity3d.com/ScriptReference/Physics.CapsuleCast.html please use whatever overload you find comfortable 
                   if (Physics.CapsuleCast(p1, p2, charContr.radius, transform.forward, out hit, 10))
    {
                        distanceToObstacle = hit.distance;
               // Then get the ortho to the vector of the using cross product 
             Vector3 direction = newVector.position - previousVector.position;
             Vector3 right = -(Vector3.Cross(direction, Vector3.up).normalized);
             
             // now you have the ortho right of the vector now a new position should be 
             // the vector you need.. hopefully this helps 
             
    }
        }

PS:new here 将致力于打开编辑器并尽快提供更具体的代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-08
    • 2011-09-12
    • 1970-01-01
    • 2021-04-02
    • 2021-07-06
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多