Home Game Development Cardboard VR Projects for Android

Cardboard VR Projects for Android

By Jonathan Linowes , Matt Schoen
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Virtual Reality for Everyone
About this book
Google Cardboard is a low-cost, entry-level media platform through which you can experience virtual reality and virtual 3D environments. Its applications are as broad and varied as mobile smartphone applications themselves. This book will educate you on the best practices and methodology needed to build effective, stable, and performant mobile VR applications. In this book, we begin by defining virtual reality (VR) and how Google Cardboard fits into the larger VR and Android ecosystem. We introduce the underlying scientific and technical principles behind VR, including geometry, optics, rendering, and mobile software architecture. We start with a simple example app that ensures your environment is properly set up to write, build, and run the app. Then we develop a reusable VR graphics engine that you can build upon. And from then on, each chapter is a self-contained project where you will build an example from a different genre of application, including a 360 degree photo viewer, an educational simulation of our solar system, a 3D model viewer, and a music visualizer. Given the recent updates that were rolled out at Google I/O 2016, the authors of Cardboard VR Projects for Android have collated some technical notes to help you execute the projects in this book with Google VR Cardboard Java SDK 0.8, released in May 2016. Refer to the article at https://www.packtpub.com/sites/default/files/downloads/GoogleVRUpdateGuideforCardbook.pdf which explains the updates to the source code of the projects.
Publication date:
May 2016
Publisher
Packt
Pages
386
ISBN
9781785887871

 

Chapter 1. Virtual Reality for Everyone

Welcome to the exciting new world of virtual reality! We're sure that, as an Android developer, you want to jump right in and start building cool stuff that can be viewed using Google Cardboard. Your users can then just slip their smartphone into a viewer and step into your virtual creations. Before we get up to our elbows in the code and tech stuff throughout the rest of this book, let's take an outside-in tour of VR, Google Cardboard, and its Android SDK to see how they all fit together. We will discuss the following topics in this chapter:

  • Why is it called Cardboard?

  • The spectrum of virtual reality devices

  • A gateway to VR

  • The value of low-end VR

  • Cardware

  • Configuring your Cardboard viewer

  • Developing apps for Cardboard

  • An overview of VR best practices

 

Why is it called Cardboard?


It all started in early 2014 when Google employees, David Coz and Damien Henry, in their spare time, built a simple and cheap stereoscopic viewer for the Android smartphones. They designed a device that can be constructed from ordinary cardboard, plus a couple of lenses for your eyes, and a mechanism to trigger a button "click." The viewer is literally made from cardboard. They wrote software that renders a 3D scene with a split screen: one view for the left eye, and another view, with offset, for the right eye. Peering through the device, you get a real sense of 3D immersion into the computer generated scene. It worked! The project was then proposed and approved as a "20% project" (where employees may dedicate one day a week for innovations), funded, and joined by other employees.

Note

Two sources of "canonical" facts about the story behind how Cardboard came into existence are as follows:

In fact, Cardboard worked so well that Google decided to go forward, taking the project to the next level and releasing it to the public a few months later at Google I/O 2014. The following figure shows a typical unassembled Google Cardboard kit:

Since its inception, Google Cardboard has been accessible to hackers, hobbyists, and professional developers alike. Google open sourced the viewer design for anyone to download the schematics and make their own, from a pizza box or from whatever they had lying around. One can even go into business selling precut kits directly to consumers. An assembled Cardboard viewer is shown in the following image:

The Cardboard project also includes a software development kit (SDK) that makes it easy to build VR apps. Google has released continuous improvements to the software, including both a native Java SDK as well as a plugin for the Unity 3D game engine (https://unity3d.com/).

Since the release of Cardboard, a huge number of applications have been developed and made available on the Google Play Store. At Google I/O 2015, Version 2.0 introduced an upgraded design, improved software, and support for Apple iOS.

Google Cardboard has rapidly evolved in the eye of the market from an almost laughable toy into a serious new media device for certain types of 3D content and VR experiences. Google's own Cardboard demo app has been downloaded millions of times from the Google Play Store. The New York Times distributed about a million cardboard viewers with its November 8, Sunday issue back in 2015.

Cardboard is useful for viewing 360-degree photos and playing low-fidelity 3D VR games. It is universally accessible to almost anyone because it runs on any Android or iOS smartphone.

Developers are now integrating 3D VR content directly into Android apps. Google Cardboard is a way of experiencing virtual reality that is here to stay.

 

The spectrum of VR devices


As with most technologies, there is a spectrum of products for virtual reality ranging from the simplest and least expensive to the very advanced.

Old fashioned stereoscopes

Cardboard is at the low end of the VR device spectrum. Well, you could even go lower if you consider the ViewMaster that you may have played with as a child, or even the historic stereoscope viewer from 1876 (B.W. Kilborn & Co, Littleton, New Hampshire), as shown in the following image:

In these old fashioned viewers, a pair of photographs display two separate views for the left and right eyes that are slightly offset to create parallax. This fools the brain into thinking that it's seeing a truly three-dimensional view. The device contains separate lenses for each eye that allow you to easily focus on the photo close up.

Similarly, rendering these side-by-side stereo views is the first job of a Google Cardboard application. (Leveraging their legacy, Mattel recently released a Cardboard-compatible ViewMaster brand VR viewer that uses a smartphone, which can be found at http://www.view-master.com/).

Cardboard is mobile VR

Cardboard's obvious advantages over stereoscopic viewers are like the advantages of digital photographs over traditional ones. Digital media can be dynamically stored, loaded, and manipulated right within our smartphones. That's a powerful leap on its own.

On top of that, Cardboard uses the motion sensors in the phone in such a way that when you turn your head left-right or up-down, the image is adjusted accordingly, effectively obliterating the traditional frame edges of the image. Framing the image is a very important part of traditional visual media, such as painting, photography, and cinematography. For centuries, artists and directors have established a visual language using this rectangular frame.

However, not so much in VR. When you move your head in VR your view direction changes, and the scene is updated as if the camera is rotating along with you, providing a fully immersive view. You can rotate it horizontally 360 degrees as you look side to side and 180 degrees up and down. In other words, you can look anywhere you want. There is no frame in VR! (Albeit your peripheral vision might be limited by the optics and display size, which determine the device's field of view or FOV). In this way, the design considerations may be more akin to sculpture, theatre-in-the-round, or even architectural design. We need to think about the whole space that immerses the visitor.

The Google Cardboard device is simply a casing for you to slip your smartphone into. It uses the smartphone's technology, including the following:

  • Display

  • CPU (the main processor)

  • GPU (the graphics processor)

  • IMU (the motion sensor)

  • Magnetometer and/or touchscreen (the trigger sensor)

We'll talk more about how all this works a little later.

Using a mobile smartphone for VR means great things, such as ease of use, but also annoying constraints, such as limited battery life, slower graphics processing, and lower accuracy/higher latency motion sensors.

The Samsung Gear VR is a mobile VR headset that is smarter than a simple Cardboard viewer. Android-based but not compatible with Cardboard apps (and only works with specific models of Samsung phones), it has a separate built-in higher precision IMU (motion sensor), which increases the accuracy of the head motion tracking and helps reduce the motion-to-pixel latency when updating the display. It's also ergonomically designed for more extended use and it includes a strap.

Desktop VR and beyond

At the higher end of consumer virtual reality devices are the Oculus Rift, HTC Vive, and Sony PlayStation VR, among others. These products go beyond what Cardboard can do because they're not limited by the capabilities of a smartphone. Sometimes referred to as "desktop VR," these devices are head-mounted displays (HMD) tethered to an external PC or console.

On desktop VR, the desktop's powerful CPU and GPU do the actual computation and graphics rendering and send the results to the HMD. Furthermore, the HMD has higher quality motion sensors and other features that help reduce the latency when updating the display at, say, 90 frames per second (FPS). We'll learn throughout this book that reducing latency and maintaining high FPS are important concerns for all VR development and the comfort of your users on all VR devices, including Cardboard.

Desktop VR devices also add positional tracking. The Cardboard device can detect the rotational movement on any of the X, Y, and Z axes, but it unfortunately cannot detect the positional movement (for example, sliding along any of these axes). The Rift, Vive, and PSVR can. The Rift, for example, uses an external camera to track the position using infrared lights on the HMD (outside-in tracking). The Vive, on the other hand, uses sensors on the HMD to track a pair of laser emitters placed strategically in the room (inside-out tracking). The Vive also uses this system to track the position and rotation of a pair of hand controllers. Both strategies achieve similar results. The user has a greater freedom to move around within the tracked space while experiencing moving around within the virtual space. Cardboard cannot do this.

Note that innovations are continually being introduced. Very likely, at some point, positional tracking will be included with the Cardboard arsenal. For example, we know that Google's Project Tango implements visual-inertial odometry, or VIO, using sensors, gyroscopes, and awareness of the physical space to provide motion and positional tracking to mobile apps. Refer to https://developers.google.com/project-tango/overview/concepts. Mobile device companies, such as LG and Samsung, are working hard to figure out how to do mobile positional tracking, but (at the time of this writing) a universal, low-latency solution does not yet exist. Google's Project Tango shows some promise but cannot yet achieve the time-to-pixel latency required for a smooth, comfortable VR experience. Too much latency and you get sick!

At the very high end are industrial and military grade systems that cost thousands or millions of dollars, which are not consumer devices, and I'm sure can do really awesome things. I could tell you more about it, but then I'd have to kill you. Solutions such as these have also been around since the 1980s. VR is not new—consumer VR is new.

The spectrum of VR devices is illustrated in the following diagram:

When we develop for Cardboard, it is important to keep in mind the things it can and cannot do relative to other VR devices. Cardboard can display stereoscopic views. Cardboard can track rotational head movement. It cannot do positional tracking. It has limitations of graphics processing power, memory, and battery life.

 

A gateway to VR


In the very short time it has been available, this generation of consumer virtual reality has demonstrated itself to be instantly compelling, immersive, entertaining, and "a game changer" for just about everyone who tries it. Google Cardboard is especially easy to access with a very low barrier to use. All you need is a smartphone, a low-cost Cardboard viewer (as low as $5 USD), and free apps downloaded from Google Play (or Apple App Store for iOS).

Google Cardboard has been called a gateway to VR, perhaps in reference to marijuana as a "gateway drug" to more dangerous illicit drug abuse? We can play with this analogy for a moment, however decadent. Perhaps Cardboard will give you a small taste of VR's potential. You'll want more. And then more again. This will help you fulfill your desire for better, faster, more intense, and immersive virtual experiences that can only be found in higher end VR devices. At this point, perhaps there'll be no turning back; you're addicted!

Yet as a Rift user, I still also enjoy Cardboard. It's quick. It's easy. It's fun. And it really does work, provided I run apps that are appropriately designed for the device.

I brought a Cardboard viewer in my backpack when visiting my family for the holidays. Everyone enjoyed it a lot. Many of my relatives didn't even get past the standard Google Cardboard demo app, especially its 360-degree photo viewer. That was engaging enough to entertain them for a while. Others jumped to a game or two or more. They wanted to keep playing and try new experiences. Perhaps it's just the novelty. Or, perhaps it's the nature of this new medium. The point is that Google Cardboard provides an immersive experience that's enjoyable, useful, and very easily accessible. In short, it is amazing.

Then, show them an HTC Vive or Oculus Rift. Holy Cow! That's really, really amazing! Well, for this book, we're not here to talk about the higher end VR devices, except to contrast them with Cardboard and to keep things in perspective.

Once you try desktop VR, is it hard to "go back" to mobile VR? Some folks say so. But that's almost silly. The fact is that they're really separate things.

As discussed earlier, desktop VR comes with much higher processing power and other high-fidelity features, whereas mobile VR is limited by your smartphone. If a developer were to try and directly port a desktop VR app to a mobile device, there's a good chance that you'll be disappointed.

It's best to think of each as a separate medium. Just like a desktop application or a console game is different from, but similar to, a mobile one. The design criteria may be similar but different. The technologies are similar but different. The user expectations are similar but different. Mobile VR may be similar to desktop VR, but it's different.

Note

To emphasize how different Cardboard is from desktop VR devices, it's worth pointing out that Google has written the following into their manufacturer's specifications and guidelines:

"Do not include a headstrap with your viewer. When the user holds the Cardboard with their hands against the face, their head rotation speed is limited by the torso rotational speed (which is much slower than the neck rotational speed). This reduces the chance of "VR sickness" caused by rendering/IMU latency and increases the immersiveness in VR."

The implication is that Cardboard apps should be designed for shorter, simpler, and somewhat stationary experiences. Throughout this book, we'll illustrate these and other tips and best practices as you develop for the mobile VR medium.

Let's now consider the other ways that Cardboard is a gateway to VR.

We predict that Android will continue to grow as a primary platform for virtual reality in the future. More and more technologies will get crammed into smartphones. And this technology will include features advantageous to VR:

  • Faster processors and mobile GPUs

  • Higher resolution screens

  • Higher precision motion sensors

  • Optimized graphics pipelines

  • Better software

  • Many more VR apps

Mobile VR will not give way to desktop VR; it may even eventually replace it.

Furthermore, we'll soon see dedicated mobile VR headsets that have the guts of a smartphone built-in without the cost of a wireless communications contract. No need to use your own phone. No more getting interrupted while in VR by an incoming call or notification. No more rationing battery life in case you need to receive an important call or otherwise use your phone. All these dedicated VR devices will likely be Android-based.

 

The value of low-end VR


Meanwhile, Android and Google Cardboard are here today on our phones, in our pockets, in our homes, at the office, and even in our schools.

Google Expeditions, for example, is Google's educational program for Cardboard (https://www.google.com/edu/expeditions/), which allows K-12 school children to take virtual field trips to "places a school bus can't," as they say, "around the globe, on the surface of Mars, on a dive to coral reefs, or back in time." The kits include Cardboard viewers and Android phones for each child in a classroom, plus an Android tablet for the teacher. They're connected with a network. The teacher can then guide students on virtual field trips, provide enhanced content, and create learning experiences that go way beyond a textbook or classroom video, as shown in the following image:

In another creative marketing example, in summer of 2015, Kellogg's began selling Nutri-Grain snack bars in a box that transforms into a Google Cardboard viewer. This links to an app that shows a variety of extreme sport 360-degree videos (http://www.engadget.com/2015/09/09/cereal-box-vr-headset/), as shown in the following image:

The entire Internet can be considered a world-wide publishing and media distribution network. It's a web of hyperlinked pages, text, images, music, video, JSON data, web services, and much more. It's also teeming with 360-degree photos and videos. There's also an ever growing amount of three-dimensional content and virtual worlds. Would you consider writing an Android app today that doesn't display images? Probably not. There's a good chance that your app also needs to support sound files, videos, or other media. So pay attention. Three-dimensional Cardboard-enabled content is coming quickly. You might be interested in reading this book now because VR looks fun. But, soon enough, it may be a customer-driven requirement for your next app.

Some examples of types of popular Cardboard apps include:

And much more; thousands more. The most popular ones have had hundreds of thousands of downloads (the Cardboard demo app itself has millions of downloads).

The projects in this book are examples of different kinds of Cardboard apps that you can build yourself today.

 

Cardware!


Let's take a look at the different Cardboard devices that are available. There's a lot of variety.

Obviously, the original Google design is actually made from cardboard. And manufacturers have followed suit, offering cardboard Cardboards directly to consumers—brands such as Unofficial Cardboard, DODOCase, and IAmCardboard were among the first.

Google provides the specifications and schematics free of charge (refer to https://www.google.com/get/cardboard/manufacturers/). For example, the Version 2.0 Viewer Body schematic is shown as follows:

The basic viewer design consists of an enclosure body, two lenses, and an input mechanism. The Works with Google Cardboard certification program indicates that a given viewer product meets the Google standards and works well with Cardboard apps.

The viewer enclosure may be constructed from any material: cardboard, plastic, foam, aluminum, and so on. It should be lightweight and do a pretty good job of blocking the ambient light.

The lenses (I/O 2015 Edition) are 34 mm diameter aspherical single lenses with an 80 degree circular FOV (field of view) and other specified parameters.

The input trigger ("clicker") can be one of several alternative mechanisms. The simplest is none, where the user must touch the smartphone screen directly with her finger to trigger a click. This may be inconvenient since the phone is sitting inside the viewer enclosure but it works. Plenty of viewers just include a hole to stick your finger inside. Alternatively, the original Cardboard utilized a small ring magnet attached to the outside of the viewer, held in place by an embedded circular magnet. The user can slide the ring magnet, and the change in magnetic field is sensed by the phone's magnetometer and recognized by the software as a "click". This design is not always reliable because the location of the magnetometer varies among phones. Also, using this method, it is harder to detect a "press and hold" interaction, which means that there is only one type of user input "event" to use within your application.

Cardboard Version 2.0 introduced a button input constructed from a conductive "strip" and "pillow" glued to a Cardboard-based "hammer," like the ones in a grand piano. When the button is pressed, the user's body charge is transferred onto the smartphone screen, as if he'd directly touched the screen with his finger. This clever solution avoids the unreliable magnetometer solution, and instead it uses the phone's native touchscreen input, albeit indirectly.

It is also worth mentioning at this point that, since your smartphone supports Bluetooth, it's possible to use a handheld Bluetooth controller with your Cardboard apps. This is not part of the Cardboard specifications and requires some extra configuration: the use of a third-party input handler or controller support built into the app. A mini Bluetooth controller is shown in the following image:

Cardboard viewers are not necessarily made out of cardboard. Plastic viewers can get relatively costly. While they are more sturdy than cardboard they fundamentally have the same design (assembled). Some devices allow you to adjust the distance from the lenses to the screen, and/or the distance between your eyes (IPD or inter-pupillary distance). The Zeiss VR One, Homido, and Sunnypeak devices were among the first to become popular.

Some manufacturers have gone outside the box (pun intended) with innovations that are not necessarily compliant with Google's specifications but provide capabilities beyond the Cardboard design. A notable example is the Wearality viewer (http://www.wearality.com/), which includes a patented 150-degree field of view (FOV) double Fresnel lens. It's so portable that it folds up like a pair of sunglasses. A pre-release version of the Wearality viewer is shown in the following image:

 

Configuring your Cardboard viewer


With such a variety of Cardboard devices and variations in lens distance, field of view, distortion, and so on, Cardboard apps must be configured to a specific device's attributes. Google provides a solution to this as well. Each Cardboard viewer comes with a unique QR code and/or NFC chip which you scan to configure the software for that device. If you're interested in calibrating your own device or customizing your parameters, check out the profile generator tools at https://www.google.com/get/cardboard/viewerprofilegenerator/.

To configure your phone to a specific Cardboard viewer, open the standard Google Cardboard app, and select the Settings icon in the bottom center section of the screen, as shown in the following image:

Then point the camera at the QR code for your particular Cardboard viewer:

Your phone is now configured for the specific Cardboard viewer parameters.

 

Developing apps for Cardboard


At the time of writing this book, Google provides two SDKs for Cardboard:

Let's consider the Unity option first.

Using Unity

Unity (http://unity3d.com/) is a popular full-featured 3D game engine, which supports building your games on a wide gamut of platforms, from PlayStation and XBox, to Windows and Mac (and Linux!), to Android and iOS.

Unity consists of many separate tools integrated into a powerful engine under a unified visual editor. There are tools for graphics, physics, scripting, networking, audio, animations, UI, and much more. It includes advanced computer graphics rendering, shading, textures, particles, and lighting with all kinds of options for optimizing performance and fine tuning the quality of your graphics for both 2D and 3D. If that's not enough, Unity hosts a huge Asset Store teeming with models, scripts, tools, and other assets created by its large community of developers.

The Cardboard SDK for Unity provides a plugin package that you can import into the Unity Editor, containing prefabs (premade objects), C# scripts, and other assets. The package gives you what you need in order to add a stereo camera to your virtual 3D scene and build your projects to run as Cardboard apps on Android (and iOS). Unity is planning on integrating the Cardboard SDK directly into the engine, which means that adding support for Cardboard will be possible by just checking a box in the build settings.

Note

If you're interested in learning more about using Unity to build VR applications for Cardboard, check out another book by Packt Publishing, Unity Virtual R eality Projects by Jonathan Linowes (https://www.packtpub.com/game-development/unity-virtual-reality-projects).

Going native

So, why not just use Unity for Cardboard development? Good question. It depends on what you're trying to do. Certainly, if you need all the power and features of Unity for your project, it's the way to go.

But at what cost? With great power comes great responsibility (says Uncle Ben Parker). It is quick to learn but takes a lifetime to master (says the Go Master). Seriously though, Unity is a powerful engine that may be overkill for many applications. To take full advantage, you may require additional expertise in modeling, animation, level design, graphics, and game mechanics.

Cardboard applications built with Unity are bulky. An empty Unity scene build for Android generates an .apk file that is a minimum of 23 megabytes. In contrast, the simple native Cardboard application, .apk, that we build in Chapter 2, The Skeleton Cardboard Project, is under one megabyte.

Along with this large app size comes a long loading time, possibly more than several seconds. It impacts the memory usage and battery use. Unless you've paid for a Unity Android license, your app always starts with the Made With Unity splash screen. These may not be acceptable constraints for you.

In general, the closer you are to the metal, the better performance you'll eke out of your application. When you write directly for Android, you have direct access to the features of the device, more control over memory and other resources, and more opportunities for customization and optimization. This is why native mobile apps tend to trump mobile web apps.

Lastly, one of the best reasons to develop with native Android and Java may be the simplest. You're anxious to build something now! If you're already an Android developer, then just use what you already know and love! Take the straightest path from here to there.

If you're familiar with Android development, then Cardboard development will come naturally. Using the Cardboard SDK for Android, you can program in Java, using the Android Studio IDE (integrated development environment), which is based on InteliJ IDEA by Jet Brains.

As we'll see throughout this book, your Cardboard Android app is like other Android apps, including a manifest, resources, and Java code. As with any Android app, you will implement a MainActivity class, but yours will extend CardboardActivity and implement CardboardView.StereoRenderer. Your app will utilize OpenGL ES 2.0 graphics, shaders, and 3D matrix math. It will be responsible for updating the display on each frame, that is, rerendering your 3D scene based on the direction the user is looking at that particular slice in time. It is particularly important in VR, but also in any 3D graphics context, to render a new frame as quickly as the display allows, usually at 60 FPS. Your app will handle the user input via the Cardboard trigger and/or gaze-based control. We'll go into the details of all these topics in the upcoming chapters.

That's what your app needs to do. However, there are still more nitty gritty details that must be handled to make VR work. As noted in the Google Cardboard SDK guide (https://developers.google.com/cardboard/android/), the SDK simplifies many of these common VR development tasks, including the following:

  • Lens distortion correction

  • Head tracking

  • 3D calibration

  • Side-by-side rendering

  • Stereo geometry configuration

  • User input event handling

Functions are provided in the SDK to handle these tasks for you.

Building and deploying your applications for development, debugging, profiling, and eventually publishing on Google Play also follow the same Android workflows you may be familiar with already. That's cool.

Of course, there's more to building an app than simply following an example. We'll take a look at techniques such as using data-driven geometric models, abstracting shaders and OpenGL ES API calls, and building user interface elements with gaze-based selection. On top of all this, there are important suggested best practices for making your VR experiences work and avoiding common mistakes.

 

An overview to VR best practices


More and more is being discovered and written each day about the dos and don'ts when designing and developing for VR. Google provides a couple of resources to help developers build great VR experiences, including the following:

VR motion sickness is a real symptom and concern for virtual reality caused in part by a lag in screen updates, or latency, when you're moving your head. Your brain expects the world around you to change exactly in sync with your actual motion. Any perceptible delay can make you feel uncomfortable, to say the least, and possibly nauseous. Latency can be reduced by faster rendering of each frame to maintain the recommended frames per second. Desktop VR apps are held to the high standard of 90 FPS, enabled by a custom HMD screen. On mobile devices, the screen hardware often limits refresh rates to 60 FPS, or in the worst case, 30 FPS.

There are additional causes of VR motion sickness and other user discomforts, which can be mitigated by following these design guidelines:

  • Always maintain head tracking. If the virtual world seems to freeze or pause, this may cause users to feel ill.

  • Display user interface elements, such as titles and buttons, in 3D virtual space. If rendered in 2D, they'll seem to be "stuck to your face" and you will feel uncomfortable.

  • When transitioning between scenes, fade to black. Cut scenes will be very disorienting. Fading to white might be uncomfortably bright for your users.

  • Users should remain in control of their movement within the app. Something about initiating camera motion yourself helps reduce motion sickness. Try to avoid "artificially" rotating the camera.

  • Avoid acceleration and deceleration. As humans, we feel acceleration but not constant velocity. If you are moving the camera inside the app, keep it at a constant velocity. Rollercoasters are fun, but even in real life they can make you feel sick.

  • Keep your users grounded. Being a virtual floating point in space can make you feel sick, whereas feeling like you're standing on the ground or sitting in a cockpit provides a sense of stability.

  • Maintain a reasonable distance from the eye for UI elements, such as buttons and reticle cursors. If objects are too close, the user may have to look cross-eyed and can experience eye strain. Some items that are too close may not converge at all and cause "double-vision."

Applications for virtual reality also differ from conventional Android apps in other ways, such as:

  • When transitioning from a 2D application into VR, it is recommended that you provide a headset icon for the user to tap, as shown in the following image:

  • To exit VR, the user can hit the back button in the system bar (if present) or the home button. The cardboard sample apps use a "tilt-up" gesture to return to the main menu, which is a fine approach if you want to allow a "back" input without forcing the user to remove the phone from the device.

  • Make sure that you build your app to run in fullscreen mode (and not in Android's Lights Out mode).

  • Do not perform any API calls that will present the user with a 2D dialog box. The user will be forced to remove the phone from the viewer to respond.

  • Provide audio and haptic (vibration) feedback to convey information and indicate that the user input is recognized by the app.

So, let's say that you've got your awesome Cardboard app done and it is ready to publish. Now what? There's a line you can put in the AndroidManifest file that marks the app as a Cardboard app. Google's Cardboard app includes a Google Play Store browser used to find a Cardboard app. Then just publish it as you would do for any normal Android application.

 

Summary


In this chapter, we started by defining Google Cardboard and saw how it fits in the spectrum of consumer virtual reality devices. We then contrasted Cardboard with higher end VR devices, such as Oculus Rift, HTC Vive, and PlayStation VR, making the case for low-end VR as a separate medium in its own right. There are a variety of Cardboard viewer devices on the market, and we looked at how to configure your smartphone for your viewer using QR codes. We talked a bit about developing for Cardboard, and considered why and why not to use the Unity 3D game engine versus writing a native Android app in Java with the Cardboard SDK. Lastly we took a quick survey of many design considerations for developing for VR that we'll talk more about throughout the book, including ways to avoid motion sickness and tips for integrating Cardboard with Android apps in general.

In the next chapter we start coding. Yaay! For a common point of reference, we'll spend a little time introducing the Android Studio IDE and reviewing the Cardboard Android classes. Then together we'll build a simple Cardboard app, as we lay the groundwork for the structure and function of other projects throughout the book.

About the Authors
  • Jonathan Linowes

    Jonathan Linowes is a VR/AR enthusiast, Unity, and full stack developer, entrepreneur, certified Unity instructor, and the owner of Parkerhill XR Studio, an immersive media, applications, and game developer. Jonathan has a bachelor of fine arts degree from Syracuse University, a master of science degree from the MIT Media Lab, and has held technical leadership positions at Autodesk and other companies. He has authored multiple books on VR and AR published by Packt Publishing.

    Browse publications by this author
  • Matt Schoen

    Matt Schoen is the cofounder of Defective Studios and has been making VR apps since the early DK1 days. Still in the early stages of his career, he spent most of his time working on Unity apps and games, some for hire and some of his own design. He studied computer engineering at Boston University and graduated with a BS in 2010, at which point he founded Defective with Jono Forbes, a high-school friend. He has been making games and apps ever since. Matt was the technical lead on Defective's debut game, CosmoKnots, and remains involved in Jono's pet project, Archean. This is his first foray into authorship, but he brings with him his experience as an instructor and curriculum designer for Digital Media Academy. Jono and Matt have recently joined Unity's VR Labs division, where they will be helping to create experimental new features which will shape the VR landscape for years to come.

    Browse publications by this author
Latest Reviews (4 reviews total)
Cardboard VR Projects for Android
Unlock this book and the full library FREE for 7 days
Start now