【VR-Unity-Google VR SDK】Cardboar

本文的流程是这样的:
- 准备
- 开始制作最简单的 VR 盒子
- 添加凝视事件
- 运行与测试
- 发布到手机并测试
- 结束
- 下载
本文的测试环境:
- macOS Mojave 10.14.3 / MacBook Pro 2015
- Unity 2018.3.9f1
- VR 盒子:VR Shinecon Virtual Reality Glasses
- 测试安卓机:360手机 N4S 骁龙版
准备
我们要制作的是一个最简单的 VR 盒子程序,只能看,不能点的那种,因为最简单的 VR 盒子就是这样,没有外设嘛。
本文开始之前呢,约定读者掌握了 Unity 的基础知识,比如创建项目,创建脚本之类的。
本文开始之前,你需要准备以下这些东西:
- GoogleVRForUnity_*.unitypackage
- Android SDK(如果需要的话)
- Unity 2018.3.9f1
开始制作最简单的 VR 盒子
好啦,我们开始。
打开 Unity,创建一个名为 gvr-cardboard-test
的项目:

导入 GoogleVRForUnity_*.unitypackage
:

将项目的平台设置为 Android 平台:

在项目中添加 vr sdk, 选中Edit/Project Setting/Player/XR Settings/Virtual Realty Supported
,点击加号,在弹出的列表中,选择Cardboard
:


并且在
Other Settings/Minimum API Level
中选择 Android 4.4 'KitKat' (API level 19)
或者比它更高的:
项目的已经设置完毕。
此时我们的gvr-cardboard-test
项目是一个空项目,如果现在就把它打包,在手机上运行的话:

你会发现,此时屏幕已经分屏了,可以在盒子里面看了:

我们回到项目中,此时运行 Editor 的话,Game 窗口中什么也不会动,很不方便,我们加点东西可以在 Game 中直接调试程序(, Gvr.. 的预制体可以在 Assets/GoogleVR/Prefabs
中找到。):
- 添加一个 Cube 到项目中,并为其添加一个
EventTrigger
。 - 添加一个名为 player 的 GameObject,把主摄像头挂到它下面成为 player 的子对象,并在主摄像头上添加
GvrPointerPhysicsRaycaster
脚本。 - 主摄像头下添加一个 GvrReticlePointer 作为子对象
- Player 下添加一个 GvrControllerPonter 作为子对象,它作为主摄像头的兄弟对象存在。
- 项目中在添加 GvrEventSystem、GvrEditorEmulator、GvrControllerMain,看名字就知道这些是干嘛的是吧:Gvr 的事件系统,Editor 的模拟器,Gvr 的控制入口。
- 把主摄像头的位置改为 0 0 0,把 Clipping Planes 改为 0.03。
-
将 Cube 的位置设置一下,比如 位置为 1 0 2,旋转的角度嘛,就改为 45 45 0。
项目结构
此时我们运行 Editor,按住 option/alt
来移动鼠标的话,Game 窗口的行为将模拟头部的运动,你也可以按住control
,再移动鼠标试试看:

我们注意到,我们的视线指针,也就是那个圆圈,当它移动到 Cube 上就会变大,移开则变成一个小白点:

它是白色的,可以修改一下颜色,让它变得更显眼些:选中GvrReticlePointer
,在着色器的面板上修改下颜色,比如改成红色的:

再次运行:

添加凝视事件
我们为 Cube 添加一些凝视事件,也就是视线进入,视线离开的事件;创建个脚本CubeController
,并挂着 Cube 身上,代码如下:
using UnityEngine;
public class CubeController : MonoBehaviour
{
public void SetGazedAt(bool gazedAt) => GetComponent<Renderer>().material.color = gazedAt ? Color.blue : Color.black;
}
在 Cube 的Event Trigger
中 点Add New Event Type
,添加 Pointer Enter,当然选中 Cube 这个对象,把刚写的 SetGazedAt
函数选上,并打上对勾;同样的再添加个 Pointer Exit 事件,这次不要打对勾了:

运行与测试
好啦,基本上搞定,运行程序试试效果:



一切没问题。
发布到手机并测试
打包发布到手机上:



结束
光看不能动,这种 VR 程序就没多大意思了,不要看下载个 VR 视频直接看哩(嘿嘿嘿😜)。不过,VR 盒子就是这样子的,不用其他外设,也算方便。
如果有了外设,比如说有一个按钮,就可以使用 Google VR SDK 中的 Daydream了。
下载
这里提供一下这个项目的源码,有需要的话可以在这里下载。