我们在开发的过程中经常会遇到需要更改相机的父类位置,并且需要重置通过头像控制的相机,来实现人物位置的瞬移
代码如下,
Resetposition()使用的API
ResetParentposition()直接调整父类来实现
public class ChangeTransform : MonoBehaviour
{
public Transform childTransform; // 需要在Inspector中指定子物体的Transform组件
// Start is called before the first frame update
void Start()
{
}
/// <summary>
/// 重置相机位
/// </summary>
public void Resetposition() {
XRDevice.SetTrackingSpaceType(TrackingSpaceType.Stationary);
InputTracking.Recenter();
}
/// <summary>
/// 通过调整父类让子物体位置归零
/// </summary>
public void ResetParentposition()
{
if (childTransform != null && childTransform.parent != null)
{
// 获取子物体相对于世界坐标系的旋转
Quaternion childWorldRotation = childTransform.localRotation;
// 计算逆旋转,使得子物体的世界旋转被消除
Quaternion inverseChildWorldRotation = Quaternion.Inverse(childWorldRotation);
transform.localRotation = Quaternion.identity;
// 将逆旋转应用到父物体上
transform.localRotation = inverseChildWorldRotation * transform.localRotation;
// 设置父物体的位置,使子物体保持在世界坐标原点
transform.localPosition = new Vector3(-childTransform.localPosition.x, 0, -childTransform.localPosition.z);
transform.localRotation = new Quaternion(0, transform.localRotation.y, 0, transform.localRotation.w); ;
}
}
}