用Unity给我们提供的 Input.gyro.attitude 实现游戏相机随手机旋转。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gyroscope : MonoBehaviour
{
private Quaternion gyroscopeQua; //陀螺仪四元数
private Quaternion quatMult = new Quaternion(0, 0, 1, 0); // 沿着 Z 周旋转的四元数 因子
private float speedH = 0.2f; //差值
void Start()
{
Input.gyro.enabled = true; //激活陀螺仪
transform.eulerAngles = new Vector3(90, 90, 0); //因安卓设备的陀螺仪四元数水平值为[0,0,0,0]水平向下,所以将相机初始位置修改与其对齐
}
void Update()
{
GyroModifyCamera();
}
void GyroModifyCamera() //检测陀螺仪运动的函数
{
gyroscopeQua = Input.gyro.attitude * quatMult; //为球面运算做准备
//transform.localRotation = Quaternion.Slerp(transform.localRotation, gyroscopeQua, speedH);
transform.localRotation = new Quaternion (gyroscopeQua.x, transform.localRotation.y, transform.localRotation.z, transform.localRotation.w);
}
}
随后,用 WebCamTexture 获取摄像头画面,并显示在 RawImage 上。
public class NewBehaviourScript : MonoBehaviour
{
public RawImage rawImage;
private WebCamTexture webCamTexture;
void Start()
{
StartCoroutine(CallWebCam());
}
IEnumerator CallWebCam()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
webCamTexture = new WebCamTexture();
WebCamDevice[] devices = WebCamTexture.devices; //必须要有摄像头和摄像头权限。如果没有摄像头或没有摄像头权限,将报index(索引)错误
webCamTexture.deviceName = devices[0].name;
webCamTexture.Stop(); //开始
rawImage.texture = webCamTexture;
}
}
}
完成。