我目前正在开发的产品是《青光眼白内障》,HTCCosmos版本的VR,然后现在遇到了这样子一个需求,就是体验流程中要显示的UI,如果在相机视野外,就要平滑旋转到视野内,小于视野的UI就停留在原地位置。 两段代码,两个逻辑,实现的效果都行,但是有区别,第二段优化流程,相当于UI已经跟上了头盔的转动,更倾向于第二种。
下面直接上代码: (1)
public Transform targetTran;
脚本挂载到相机
if (angle > 57)
{
if (isInView)
{
var v = transform.position - targetTran.position;
var s = Vector3.Cross(v.normalized, transform.forward);
angle *= s.y < 0 ? 1 : -1;
if (coroutine != null) StopCoroutine(coroutine);
coroutine = RotateAround(targetTran.transform, transform.position, Vector3.up, angle);
Debug.Log("不在视野范围内");
isInView = false;
}
}
else
{
Debug.Log("在视野范围内");
isInView = true;
}
private Coroutine coroutine;
private Coroutine RotateAround(Transform target, Vector3 point, Vector3 axis, float angle)
{
return StartCoroutine(CRotateAround());
IEnumerator CRotateAround()
{
var crtAngle = 0f;
while (Mathf.Abs(crtAngle - angle) > 0.02f)
{
var tmp = Mathf.Lerp(crtAngle, angle, 0.15f);
Debug.Log(crtAngle);
target.RotateAround(point, axis, tmp - crtAngle);
crtAngle = tmp;
yield return null;
}
target.RotateAround(point, axis, angle - crtAngle);
}
}
(2)
var a = transform.forward;
a.y = 0;
var b = targetTran.transform.position - transform.position;
b.y = 0;
var angle = Mathf.Acos(Vector3.Dot(a.normalized, b.normalized)) * Mathf.Rad2Deg;
if (angle >57)
kz_OnOff = true;
if(angle<3)
kz_OnOff = false;
if (kz_OnOff)
{
angle *= 0.18f;
var v = transform.position - targetTran.position;
var s = Vector3.Cross(v.normalized, transform.forward);
angle *= s.y < 0 ? 1 : -1;
targetTran.RotateAround(transform.position,Vector3.up,angle);
}
可自行体验效果差别
|