获取旋转和位置之间的差异

时间:2019-03-13 10:15:24

标签: unity3d

我在世界空间中有两个物体。 一个是没有父级的多维数据集。 第二个是三角形,它有一个父对象。 我更改立方体的位置和旋转。 现在,我需要将多维数据集放在其第一个位置,但是将父对象(局部)中的三角形移动到这样的位置以适合相同的位置,就好像该多维数据集不会放在先前的位置一样。

enter image description here

1 个答案:

答案 0 :(得分:1)

  1. Somwhere存储cube

    的原始位置和旋转
    Vector3 origPosition = cube.transform.position;
    Quaternion origRotation = cube.transform.rotation;
    
  2. 获取立方体和三角形之间的偏移值

    Vector3 posOffset = triangle.transform.position - cube.transform.position;
    Quaternion rotOffset = Quaternion.Inverse(cube.transform.rotation) * triangle.transform.rotation;
    
  3. (重新)将立方体和三角形设置到位

    cube.transform.position = origPosition;
    cube.transform.rotation = origRotation;
    
    triangle.transform.position = origPosition + posOffset;
    triangle.transform.rotation = origRotation * rotOffset;
    

示例

public class CubeMover : MonoBehaviour
{
    public Transform cube;
    public Transform triangle;

    private Vector3 origPosition;
    private Quaternion origRotation;

    // Start is called before the first frame update
    private void Start()
    {
        origPosition = cube.transform.position;
        origRotation = cube.transform.rotation;
    }

    [ContextMenu("Test")]
    public void ResetCube()
    {
        Vector3 posOffset = triangle.transform.position - cube.transform.position;
        Quaternion rotOffset = Quaternion.Inverse(cube.transform.rotation) * triangle.transform.rotation;


        cube.transform.position = origPosition;
        cube.transform.rotation = origRotation;

        triangle.transform.position = origPosition + posOffset;
        triangle.transform.rotation = origRotation * rotOffset;
    }
}

(没有三角形,所以我用了圆柱体...我希望对你没问题^^)

enter image description here

相关问题