在前面的问题中,您说过圆柱体有一个父对象,因此如前所述,您可以使用
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;
}