在VR里面,特别移动VR里面,利用按键晃动头部移动物体时,需要保持物体相对于头部相机的方向不变。把下面的脚本挂载在需要移动的物体上,按住空格键,移动旋转相机,物体相对于相机位置和方向不变。在实际开发过程中,把空格按键按下和抬起事件方法,设置成指定的移动按键就行了。
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 按住空格键,移动旋转head相机,物体相对于head相机的方向和位置保持不变.
/// 该脚本挂载在物体上。
/// </summary>
public class TestRotation : MonoBehaviour {
public GameObject head;
private Quaternion diff;
private bool isRotate = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
diff = Quaternion.FromToRotation(head.transform.forward, transform.forward);
isRotate = true;
}
if (Input.GetKeyUp(KeyCode.Space))
{
isRotate = false;
diff = Quaternion.identity;
}
if (isRotate)
{
Quaternion rotation = head.transform.rotation * diff;
transform.rotation = rotation;
transform.position = head.transform.forward * 5f + head.transform.position;
}
}
}
```