代码之家  ›  专栏  ›  技术社区  ›  Daniel

调整圆柱体变换以匹配2个给定点

  •  0
  • Daniel  · 技术社区  · 5 年前

    假设我有一个圆柱体(高度为2,长度和宽度为1),其中包含两个孩子 顶部 底部 和空间中的2个给定点 p1 第2页 ,就像这样:

    enter image description here

    我如何评估这个圆柱体的旋转,以便 顶部 首选 p1 , 底部 首选 第2页 圆柱体是否与点正确对齐?这是我想要的结果:

    enter image description here


    圆柱体的最终位置应为(p1+p2)/2,y轴应为(p1-p2).大小/2,因为圆柱体的自然高度为2。

    0 回复  |  直到 5 年前
        1
  •  0
  •   derHugo    5 年前

    在前面的问题中,您说过圆柱体有一个父对象,因此如前所述,您可以使用 Transform.LookAt

    旋转变换,使 正向矢量 指向/target/的当前位置。

    或者 Quaternion.LookRotation

    创建具有指定向前和向上方向的旋转。

    在父对象上,只需确保圆柱体旋转的方式使其局部Y轴与父对象的Z轴匹配即可=>局部旋转是 -90°, 0, 0

    或者您可以简单地将此旋转添加到的结果中 四元数。LookRotation 比如。

    private Quaternion offset = Quaternion.Euler(-90, 0, 0);
    
    public void ApplyPoints(Transform cylinder, Vector3 p1, Vector3 p2)
    {
        var delta = p2 - p1;
    
        // First apply the world space rotation so the forward vector points p1 to p2
        cylinder.rotation = Quaternion.LookRotation(delta);
        // Then add the local offset around the local X axis
        cylinder.localRotation *= offset;
        // Or also
        //cylinder.Rotate(-90, 0, 0);
    
        // Set the position to the center between p1 and p2
        cylinder.position = (p1 + p2) / 2f;
    
        // Set the Y scale to the half of the distance between p1 and p2    
        var scale = cylinder.localScale;
        scale.y = delta.magnitude / 2f;
        cylinder.localScale = scale;
    }
    

    除此之外,您也可以简单地将所需的方向指定给 Transform.up

    public void ApplyPoints(Transform cylinder, Vector3 p1, Vector3 p2)
    {
        var delta = p2 - p1;
    
        // YES! It is possible to simply set the up, right or forward direction 
        // so the object is rotated accordingly
        cylinder.up = delta;
    
        // Set the position to the center between p1 and p2
        cylinder.position = (p1 + p2) / 2f;
    
        // Set the Y scale to the half of the distance between p1 and p2    
        var scale = cylinder.localScale;
        scale.y = delta.magnitude / 2f;
        cylinder.localScale = scale;
    }