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

Adjust Cylinder transform to match 2 given points

假设我有一个圆柱体(高度为 2,长度和宽度为 1),其中包含两个 children topbottom 和 space p1p2 中的 2 个给定点,就像这样:

我如何评估这个圆柱体的旋转,以便 top 转到 p1bottom 转到 p2 并且圆柱体与点正确对齐?这是我想要的结果:


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

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

Rotates the transform so the forward vector points at /target/'s current position.

Quaternion.LookRotation

Creates a rotation with the specified forward and upwards directions.

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

或者您可以简单地将此旋转添加到 Quaternion.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;
}