检查一个平面是否与另一个平面处于相同的位置/旋转



我有两个比例相同的平面gameObject。我试图观察第一个移动平面是否围绕第二个静止平面的位置/旋转。位置和旋转是否匹配并不重要,重要的是它应该具有相同的值。例如,如果平面2的x位置为2.75,则平面1应与值2匹配。它应该具有一个偏移值,以便至少接近第二个平面。我该如何做到这一点?

public class CheckIfFits: MonoBehaviour
{
public GameObject Plane_2;
public float offset;
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
if(this.transform.position == Plane_2.transform.position && this.transform.eulerAngles == Plane_2.transform.eulerAngles)
{
Debug.Log("THEY MATCH");
}
}
}

编辑:旋转的答案并不适用于所有实例。例如,如果对象翻转或在负轴上旋转。这就是我目前所做的:

float diff = Quaternion.Angle(transform.rotation, target.rotation);
// Return true if both values are smaller than the offset.
return dist <= offset_position && ((diff <= offset_rotation && diff >= 0) || (diff <= (90+offset_rotation) && diff >= 90) || (diff <= (180+offset_rotation) && diff >= 180) || (diff <= (270+offset_rotation) && diff >= 270) || (diff <= 360 && diff >= (350+offset_rotation)));

我不知道是否有更好的方法可以做到这一点。

如果两个Vector3距离0.00001更远,则使用等号运算符==将失败。

相反,您可以使用Vector3.Distance(),然后将您获得的floatoffset进行比较,而不是直接进行比较。

CompareTransform方法:

public float offset;
// Compares 2 Transforms position and rotations.
private bool CompareTransform(Transform current, Transform target) {
// Gets the distance between 2 positions.
float dist = Vector3.Distance(current.position, target.position);
// Get the difference between the 2 rotations.
float diff = Vector3.Distance(current.eulerAngles, target.eulerAngles);
// Return true if both values are smaller than the offset.
return dist <= offset && diff <= offset;
}

您现在可以使用该方法来比较Update方法中的两个Transform组件。

函数调用:

private void Update() {
if(CompareTransform(this.transform, Plane_2.transform)) {
Debug.Log("Both planes match position with given offset.");
}
}

您也可以使用Quaternion.Angle()来获得两次旋转之间的角度,然后再次将获得的floatoffset进行比较。

四元数角度替代:

// Get the angle between the 2 rotations.
float angle = Quaternion.Angle(transform.rotation, target.rotation);

最新更新