【背景】
上一篇帖子我们介绍到让手臂和头部都能做自然的运动,但从人物的整个骨架来说,还存在问题,如果你把整个手臂或头部挪动到另一个位置,那么身体并不会跟着合理地移动,你会看到拉长了的Mesh,显得很怪异,如果真的就这样放到VR游戏中,你会看到自己会变成怪异的长手长脚。这篇帖子,我们来解决这个问题。
在Hierarchy的人物Root对象下新建一个脚本,命名为VR Rig:
脚本中写如下内容:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class VRRig : MonoBehaviour { public Transform headConstraint; public Vector3 headBodyOffset; // Start is called before the first frame update void Start() { headBodyOffset = transform.position - headConstraint.position; } // Update is called once per frame void LateUpdate() { transform.position = headConstraint.position + headBodyOffset; transform.forward = Vector3.ProjectOnPlane(headConstraint.up, Vector3.up).normalized; } }【代码解析】
headConstraint和headBodyOffset分别用来关联头部移动标记的方位和实际骨架头部方位的差向量Offset。 在Start中,我们获得headBodyOffset 的初始值为骨架位置(身体位置)-头部标记位置。 在LateUpdate中我们通过补正头部标记位置来获得实际自然的身体位置. 最后一行是为了计算投射的身体方向。(位置+方向才能得到完整的身体信息)。
【测试结果】运行游戏,试着唯一Head的Target,发现整个身体都会随着身体移动或者旋转。目的达成。