【问题标题】:Check if a plane is around the same position/rotation as other检查飞机是否与其他飞机的位置/旋转相同
【发布时间】:2020-12-11 16:43:33
【问题描述】:

我有两个具有相同比例的平面游戏对象。我试图实现查看第一个移动平面是否围绕位置/旋转作为第二个静态平面。位置和旋转是否匹配并不重要,重要的是它应该接近相同的值。例如,如果平面 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)));

不知道有没有更好的办法。

【问题讨论】:

  • “作为第二个静态平面的精确位置/旋转。位置和旋转是否匹配并不重要” 现在是哪个?您要检查它们是否完全相同,或者它们是否匹配无关紧要?
  • 对不起。我会改变我的问题。
  • @MathewHD 我确实想到了距离,但这对于计算位置很有效。轮换不是问题吗?
  • 不,它应该适用于两者,因为最后你的 eulerAngles 也只是一个 Vector3。

标签: c# unity3d


【解决方案1】:

使用等于运算符 ==,如果 2 个 Vector30.00001 更远,则会失败。

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

比较转换方法:

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() 获取两次旋转之间的角度,然后再次将您获得的float 与您的offset 进行比较。

Quaternion.Angle Alternative:

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

【讨论】:

  • 您好,谢谢您的详细回答!我不明白您的代码中偏移的概念。对我来说,如果我将偏移保持在 >= 100 左右,则位置/旋转匹配。基本上,轴的值应该围绕目标值进行匹配。这就是偏移的目的。
  • 偏移的目的就像你说的即使它们不完全一样仍然得到一个真实的,这也是它在我的代码中所做的我只是比较之间的距离旋转和位置偏移,然后查看它是否更小或更大,以检查它们是否彼此相等。
  • 啊,太好了,谢谢。我的第二架飞机旋转了 180 度,所以很混乱。 :D
  • if the 2 Vector3 are nearly the same 确切地说,如果距离小于0.00001 .. 只是为了完整性而添加;)
猜你喜欢
  • 2012-10-24
  • 2022-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多