Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Unity 2020 Virtual Reality Projects - Third Edition

You're reading from  Unity 2020 Virtual Reality Projects - Third Edition

Product type Book
Published in Jul 2020
Publisher Packt
ISBN-13 9781839217333
Pages 592 pages
Edition 3rd Edition
Languages
Author (1):
Jonathan Linowes Jonathan Linowes
Profile icon Jonathan Linowes

Table of Contents (15) Chapters

Preface 1. Virtually Everything for Everyone 2. Understanding Unity, Content, and Scale 3. Setting Up Your Project for VR 4. Using Gaze-Based Control 5. Interacting with Your Hands 6. Canvasing the World Space UI 7. Teleporting, Locomotion, and Comfort 8. Lighting, Rendering, Realism 9. Playing with Physics and Fire 10. Exploring Interactive Spaces 11. Using All 360 Degrees 12. Animation and VR Storytelling 13. Optimizing for Performance and Comfort 14. Other Books You May Enjoy
Virtually Everything for Everyone
This virtual reality thing calls into question, what does it mean to "be somewhere"?

Before cell phones, you would call someone and it would make no sense to say, "Hey, where are you?" You know where they are, you called their house, that's where they are.

So then cell phones come around and you start to hear people say, "Hello. Oh, I'm at Starbucks," because the person on the other end wouldn't necessarily know where you are because you became un-tethered from your house for voice communications.

So when I saw a VR demo, I had this vision of coming home and my wife has got the kids settled down, she has a couple minutes to herself, and she's on the couch wearing goggles on her face. I come over and tap her on the shoulder, and I'm like, "Hey, where are you?"

It's super weird. The person's sitting right in front of you, but you don't know where they are.

- Jonathan Stark, mobile expert, and podcaster

Welcome to virtual reality (VR)! In this book, we will explore what it takes to create VR experiences on our own. We will take a walk through a series of hands-on projects, step-by-step tutorials, and in-depth discussions using the Unity 3D game engine and other free or open source resources. Though VR technology is rapidly advancing, we'll try to capture the basic principles and techniques that you can use to make your VR games and applications feel immersive and comfortable.

In this first chapter, we will define VR and illustrate how it can be applied not only to games, but also to many other areas of interest and work productivity. We'll see that VR is all about immersion and presence, seemingly transporting you to a different place and experience. VR is not just for gaming—it can be applied to a wide spectrum of personal, professional, and educational applications. This chapter discusses the following topics:

  • What is virtual reality?
  • Differences between virtual realityand augmented reality
  • How VR applications may differ from VR games
  • Types of VR experience
  • Types of VR device
  • Some psychological, physiological, and technical explanations of how VR works
  • Technical skills that are necessary for the development of VR

What is virtual reality?

Today, we are witnesses to burgeoning consumer-accessible VR, an exciting technology that promises to transform in a fundamental way how we interact with information, our friends, and the world at large.

What is virtual reality? In general, VR is the computer-generated simulation of a 3D environment, which seems very real to the person experiencing it, using special electronic equipment. The objective is to achieve a strong sense of being present (presence) in the virtual environment.

Today's consumer tech VR involves wearing HMD (head-mounted display) goggles to view stereoscopic 3D scenes. You can look around by moving your head, and walk around by using hand controls or motion sensors. You are engaged in a fully immersive experience. It's as if you're really there in some other virtual world. The following photo shows me, the author, experiencing an Oculus Rift Development Kit 2 (DK2) in 2015:

VR is not new. It's been here for decades, albeit hidden away in academic research labs and high-end industrial and military facilities. It was big, clunky, and expensive. Ivan Sutherland invented the first HMD in 1965 (see https://amturing.acm.org/photo/sutherland_3467412.cfm). It was tethered to the ceiling with metal pipes! In the past, several failed attempts have been made to bring consumer-level VR products to the market:

In 2012, Palmer Luckey, the founder of Oculus VR LLC, gave a demonstration of a makeshift head-mounted VR display to John Carmack, the famed developer of the Doom, Wolfenstein 3D, and Quake classic video games. Together, they ran a successful Kickstarter campaign and released a developer kit called Oculus Rift Development Kit 1 (DK1) to an enthusiastic community. This caught the attention of investors, as well as Mark Zuckerberg (Facebook CEO), and in March 2014, Facebook bought the company for $2 billion. With no product, no customers, and infinite promise, the money and attention that it attracted helped fuel a new category of consumer products.

At the same time, others were also working on their own products, which were soon introduced to the market, including Steam's HTC VIVE, Google Daydream, Sony PlayStation VR, Samsung Gear VR, Microsoft's immersive Mixed Reality, and more. New innovations and devices that enhance the VR experience continue to be introduced.

Most of the basic research has already been done, and the technology is now affordable, thanks in large part to the mass adoption of devices that work on mobile technology. There is a huge community of developers with experience in building 3D games and mobile apps. Creative content producers are joining in and the media is talking it up. At last, virtual reality is real!

Say what? Virtual reality is real? Ha! If it's virtual, how can it be... Oh, never mind.

Eventually, we will get past the focus on the emerging hardware devices and recognize that content is king. The current generation of 3D development software (commercial, free, or open source) that has spawned a plethora of indie (independent) game developers can also be used to build nongame VR applications.

Though VR finds most of its enthusiasts in the gaming community, the potential applications reach well beyond that. Any business that presently uses 3D modeling and computer graphics will be more effective if it uses VR technology. The sense of immersive presence that is afforded by VR can enhance all common online experiences today, which includes engineering, social networking, shopping, marketing, entertainment, and business development. In the near future, viewing 3D websites with a VR headset may be as common as visiting ordinary flat websites today.

It's probably worthwhile to clarify what virtual reality is not by comparing VR with augmented reality.

Differences between virtual reality and augmented reality

A sister technology to VR is augmented reality (AR), which combines computer-generated imagery (CGI) with views of the real world. AR on smartphones has recently garnered widespread interest with the introduction of Apple's ARKit for iOS and Google ARCore for Android. Furthermore, the Vuforia AR toolkit is now integrated directly with the Unity game engine, helping to drive even more adoption of the technology. AR on a mobile device overlays the CGI on top of live video from a camera.

The latest innovations in AR are wearable AR headsets, such as Microsoft's HoloLens and Magic Leap. The computer graphics are shown directly in your field of view, not mixed into a video image. If VR headsets are like closed goggles, AR headsets are like translucent sunglasses that combine the real-world light rays with CGI.

A challenge for AR is ensuring that the CGI is consistently aligned with and mapped onto the objects in the real-world space and to eliminate latency while moving about so that they (the CGI and objects in the real-world space) stay aligned.

AR holds as much promise as VR for future applications, but it's different. Though AR intends to engage the user within their current surroundings, VR is fully immersive. In AR, you may open your hand and see a log cabin resting in your palm, but in VR, you're transported directly inside the log cabin and you can walk around inside it.

We are also beginning to see hybrid devices that combine features of VR and AR and let you switch between modes. For example, we're already seeing VR devices with pass-through video features, primarily used for setting up your play area bounds and floor level, and as a safety feature when the player goes out of bounds. The camera mounted on the HMD, generally used for spatial positioning, can be fed to the display. Be aware that the field of view of the video may be distorted, so it shouldn't be used for walking around.

If you are interested in developing applications for AR, please also refer to the author's book Augmented Reality for Developers from Packt Publishing (https://www.packtpub.com/web-development/augmented-reality-developers).

Next, we'll explore the ways in which VR can be used to improve our lives and entertainment.

Applications versus games

Consumer-level VR started with gaming. Video gamers are already accustomed to being engaged in highly interactive hyper-realistic 3D environments. VR just ups the ante.

Gamers are early adopters of high-end graphics technology. Mass production of gaming consoles and PC-based components in the tens of millions and competition between vendors leads to lower prices and higher performance. Game developers follow suit, often pushing the state of the art, squeezing every ounce of performance out of hardware and software. Gamers are a very demanding bunch, and the market has consistently stepped up to keep them satisfied. It's no surprise that many, if not most, of the current wave of VR hardware and software companies are first targeting the video gaming industry. A majority of the VR apps on the Oculus Store, such as Rift (https://www.oculus.com/experiences/rift/), GearVR (https://www.oculus.com/experiences/gear-vr/), and Google Play for Daydream (https://play.google.com/store/search?q=daydream&c=apps&hl=en), are for games. And of course, the Steam VR platform (http://store.steampowered.com/steamvr) is almost entirely about gaming. Gamers are the most enthusiastic VR advocates and seriously appreciate its potential.

Game developers know that the core of a game is the game mechanics, or the rules, which are largely independent of the skin, or the thematic topic, of the game. Game mechanics can include puzzles, chance, strategy, timing, or muscle memory. VR games can have the same mechanical elements but might need to be adjusted for the virtual environment. For example, a first-person character walking in a console video game is probably going about 1.5 times faster than their actual pace in real life. If this wasn't the case, the player would feel that the game was too slow and boring. Put the same character in a VR scene and they will feel that it is too fast; it could likely make the player feel nauseous. In VR, you want your characters to walk at a normal, earthly pace. Not all video games will map well to VR; it may not be fun to be in the middle of a hyperrealistic war zone when you're actually virtually there.

That said, VR is also being applied in areas other than gaming. Though games will remain important, nongaming applications will eventually overshadow them. These applications may differ from games in a number of ways, with the most significant having much less emphasis on game mechanics and more emphasis on either the experience itself or application-specific goals. Of course, this doesn't preclude some game mechanics. For example, the application may be specifically designed to train the user in a specific skill. Sometimes, the gamification of a business or personal application makes it more fun and effective in driving the desired behavior through competition.

In general, nongaming VR applications are less about winning and more about the experience itself.

Here are a few examples of the nongaming application areas that are proving successful in VR:

  • Travel and tourism: Visit faraway places without leaving your home. Visit art museums in Paris, New York, and Tokyo in one afternoon. Take a walk on Mars. You can even enjoy Holi, the spring festival of colors, in India while sitting in your wintery cabin in Vermont.
  • Mechanical engineering and industrial design: Computer-aided design software, such as AutoCAD and SOLIDWORKS, pioneered three-dimensional modeling, simulation, and visualization. With VR, engineers and designers can directly experience the end product before it's actually built and play with what-if scenarios at a very low cost. Consider iterating a new automobile design. How does it look? How does it perform? How does it appear when sitting in the driver's seat?
  • Architecture and civil engineering: Architects and engineers have always constructed scale models of their designs, if only to pitch the ideas to clients and investors or, more importantly, to validate the many assumptions about the design. Currently, modeling and rendering software is commonly used to build virtual models from architectural plans. With VR, the conversations with stakeholders can be so much more confident. Other personnel, such as interior designers, HVAC, and electrical engineers, can be brought into the process sooner.
  • Real estate: Real-estate agents have been quick adopters of the internet and visualization technology to attract buyers and close sales. Real-estate search websites were some of the first successful uses of the web. Online panoramic video walkthroughs of for-sale properties have been commonplace for years. With VR, I can be in New York and gauge the feel of a place to live in Los Angeles.
  • Medicine: The potential of VR for health and medicine may literally be a matter of life and death. Every day, hospitals use MRI and other scanning devices to produce models of our bones and organs that are used for medical diagnosis and possibly preoperative planning. Using VR to enhance visualization and measurement will provide a more intuitive analysis, for example. VR is especially being used for medical training, such as the simulation of surgery for medical students.

  • Mental health: VR experiences have been shown to be effective in a therapeutic context for the treatment of post-traumatic stress disorder (PTSD) in what's called exposure therapy, where the patient, guided by a trained therapist, confronts their traumatic memories through the retelling of the experience. Similarly, VR is being used to treat arachnophobia (fear of spiders) and the fear of flying.
  • Education: The educational opportunities for VR are almost too obvious to mention. One of the first successful VR experiences is Titans of Space, which lets you explore the solar system first hand. In science, history, the arts, and mathematics, VR will help students of all ages because, as they say, field trips are much more effective than textbooks.
  • Training: Toyota has demonstrated a VR simulation of drivers' education to teach teenagers about the risks of distracted driving. In another project, vocational students got to experience the operating of cranes and other heavy construction equipment. Training for first responders, the police, and fire and rescue workers can be enhanced with VR by presenting highly risky situations and alternative virtual scenarios. The National Football League (NFL) and college teams are looking to VR for athletic training.
  • Entertainment and journalism: Virtually attend rock concerts and sporting events or watch music videos. Re-experience news events as if you were personally present. Enjoy 360-degree cinematic experiences. The art of storytelling will be transformed by virtual reality.

Wow, that's quite a list! This is just the low-hanging fruit. Unity Technologies, the company behind the Unity 3D engine, appreciates this and is making an all-out push beyond gaming for its engine (you can learn more about Unity Solutions at https://unity.com/solutions).

The purpose of this book is not to dive too deeply into any of these applications. Rather, I hope that this brief look at the possibilities helps stimulate your thinking and provides an idea of how VR has the potential to be virtually anything for everyone. Next, we'll attempt to define the spectrum of the types of VR experience.

Types of VR experience

There is not just one kind of VR experience. In fact, there are many. Consider the following types of VR experiences:

  • Diorama: In the simplest case, webuilda 3D scene. You're observing from a third-person perspective. Your eye is the camera. Actually, each eye is a separate camera that gives you a stereoscopic view. You can look around.
  • First-person experience: This time, you'reimmersedin the scene as a freely moving agent. Using an input controller (a hand controller or some other technique), you can "walk" around and explore the virtual scene.
  • Room scale: The first-person experience with physical space. Given positional tracking, you can physically walk around a predefined area. A guardian system will show when you've reached unsafe boundaries.
  • Interactive virtual environment: This islikethe first-person experience, but you're more than an observer. While you are in the scene, you can interact with the objects in it. Physics is at play. Objects may respond to you. You may be given specific goals to achieve and challenges to face using the game mechanics. You might even earn points and keep score.
  • 3D content creation: In VR, you can create content that can be experienced in VR.Google Tilt Brushis one of the first blockbuster experiences, as isOculus MediumandGoogle Blocks, among others. Unity is working onEditorXRfor Unity developers to work on their projects directly in the VR scene.
  • Riding on rails: In thiskindof experience, you're seated and being transported through the environment (or the environment changes around you). For example, you can ride a rollercoaster using this VR experience. However, it may not necessarily be an extreme thrill ride; it could be a simple real estate walk-through or even a slow, easy, and meditative experience.
  • 360-degree media: Thinkpanoramicimages that are projected on the inside of a sphere. You're positioned at the center of the sphere and can look all around. Some purists don't consider thisreal VR, because you're seeing a projection and not a model rendering. However, it can provide an effective sense of presence.
  • Social VR: When multipleplayersenter the same VR space and can see and speak with each other's avatars, it becomes a remarkable social experience.

In this book, we will implement a number of projects that demonstrate how to build each of these types of VR experience. For brevity, we'll need to keep it pure and simple, with suggestions for areas for further investigation. Our focus will be on consumer-grade devices, described in the next section.

Types of HMD

Presently, there are two basic categories of HMDs for VR: desktop VR and mobile VR, although the distinctions are increasingly becoming blurred. Eventually, we might just talk about platforms as we do traditional computing, in terms of the operating system—for example, Windows, Android, and console VR. Let's look at each of these HMDs in more detail.

Desktop VR

With desktop VR (and console VR), yourheadsetis peripheral to a more powerful computer that processes the heavy graphics. The computer may be a Windows PC, Mac, Linux, or a game console, although Windows is by far the most prominent PC, and PlayStation is a bestseller intermsof console VR.

The headset is connected to the computer with physical wires (tethered connection) or a near-zero latency wireless connection. The game runs on the remote machine and the HMD is aperipheraldisplay device with a motion-sensing input. The termdesktopis an unfortunate misnomer since it's just as likely to be stationed in your living room or den.

TheOculus Rift(https://www.oculus.com/) is anexampleof a device where the goggles have anintegrateddisplay and sensors. The games run on a separate PC. Other desktop headsetsincludethe HTC VIVE, Sony'sPlayStation VR, andMicrosoft Mixed Reality.

Desktop VR devicesrelyon a desktop computer for CPU (general processor) and GPU (graphics processing unit) power, where more is better. Please refer to the recommended specificationrequirementsfor your specific device.

However, for the purpose of this book, we won't have any heavy rendering in our projects, and you can get by with the minimum system specifications.

Mobile VR

Mobile VR originated with Google Cardboard(https://vr.google.com/cardboard/), a simple housing device for two lenses and a slot for yourmobilephone. The phone'sdisplay shows twin stereoscopic views. It has rotational head tracking, but ithasno positional tracking. Cardboard also provides the user with the ability to click ortapits side to make selections in a game. The complexity of the imagery is limited because it uses your phone's processor for rendering the views on the phone display screen.

Google Daydream can be said to have progressed to the Samsung GearVR, requiring more performant minimum specifications in the Android phone, including greater processing power. GearVR's headsets include motion sensors to assist the phone device rather than relying on the phone's own sensors. These devices alsointroduceda three-degrees-of-freedom(DOF)hand controller that can be used as a laser pointer within VR experiences:

The term degrees of freedom (DoF) refers to the number of basic ways a rigid object can move through 3D space. There are six total degrees of freedom. Three correspond to rotational movement around the x, y, and z axes, commonly termed pitch, yaw, and roll. The other three correspond to translational movement along those axes, which can be thought of as moving forward or backward, moving left or right, and moving up or down.
Since the previous edition of this book, Google has discontinued the Daydream headset and has mad the Cardboard software open-source. Likewise, Samsung and Oculus have discontinued support for GearVR, supplanted by the Oculus Go and Quest devices.

The next generation of mobile VR devices includes all-in-one headsets, such as Oculus Go, with embedded screens and processors, eliminating the need for a separate mobile phone. The Oculus Quest further adds depth sensors and spatial mapping processors to track the user's location in 3D space, 6DOF hand controllers, and in some cases even hand tracking without hand controllers.

As of December 2020, Oculus is sunsetting the Oculus Go and will stop accepting new applications in its store.

The bottom line is that the projects in this book will explore features from the high end to the low end of the consumer VR device spectrum. But generally, our projects will not demand a lot of processing power, nor will they require high-end VR capability, so you can begin developing for VR on any of these types of devices,including Google Cardboard and an ordinary mobile phone.

Next, let's dive a little deeper into how this technology works.

How virtual reality works

So, what is it about VR that's got everyone so excited? With your headset on, you experience synthetic scenes. It appears 3D, it feels 3D, and maybe you will even have a sense of actually being there inside the virtual world. The strikingly obvious thing is that VR looks and feels really cool! But why?

Immersion and presence are the two words that are used to describe the quality of a VR experience. The Holy Grail is to increase both to the point where it seems so real that you forget you're in a virtual world. Immersion is the result of emulating the sensory input that your body receives (visual, auditory, motor, and so on). This can be explained technically. Presence is the visceral feeling that you get of being transported there—a deep emotional or intuitive feeling. You could say that immersion is the science of VR and presence is the art. And that, my friend, is cool.

A number of different technologies and techniques come together to make the VR experience work, which can be separated into two basic areas:

  • 3D viewing
  • Head, hand, and body tracking

In other words, displays and sensors, such as those built into today's mobile devices, are a big reason why VR is possible and affordable today.

Suppose that the VR system knows exactly where your head and hands are positioned at any given moment in time. Suppose that it can immediately render and display the 3D scene for this precise viewpoint stereoscopically. Then, wherever and whenever you move, you'll see the virtual scene exactly as you should. You will have a nearly perfect visual VR experience. That's basically it. Ta-dah!

Well, not so fast. Literally. Let's dig deeper into some of the psychological, physiological, and technical aspects that make VR work.

Stereoscopic 3D viewing

Split-screen stereography was discovered not long after the invention of photography. Take a look at the popular stereograph viewer from 1876 shown in the following photo (B.W. Kilborn & Co, Littleton, New Hampshire; see http://en.wikipedia.org/wiki/Benjamin_W._Kilburn):

A stereo photograph has separate views for the left and right eyes, which are slightly offset to create a parallax effect. This fools the brain into thinking that it's a truly three-dimensional view. The device contains separate lenses for each eye, which lets you easily focus on the photo close up.

Similarly, rendering these side-by-side stereo views is the first job of the VR-enabled camera object in Unity.

Let's say that you're wearing a VR headset and you're holding your head very still so that the image looks frozen. It still appears better than a simple stereograph. Why?

The old-fashioned stereograph has relatively small twin images rectangularly bound. When your eye is focused on the center of the view, the 3D effect is convincing, but you will see the boundaries of the view. Move your eyes around (even with your head still), and any remaining sense of immersion is totally lost. You're just an observer on the outside peering into a diorama.

Now, consider what a VR screen looks like without the headset by using the following screenshot:

The first thing that you will notice is that each eye has a barrel-shaped view. Why is that? The headset lens is a very wide-angle lens, so when you look through it, you have a nice wide field of view. In fact, it is so wide (and tall) that it distorts the image (pincushion effect). The graphics software inverts that distortion by creating a barrel distortion so that it looks correct to us through the lenses. This is referred to as an ocular distortion correction. The result is an apparent field of view (FOV) that is wide enough to include a lot more of your peripheral vision. For example, the Oculus Rift has an FOV of about 100 degrees (we talk more about FOV in Chapter 11, Using All 360 Degrees).

Also, of course, the view angle from each eye is slightly offset, comparable to the distance between your eyes or the inter pupillary distance (IPD). The IPD is used to calculate the parallax and can vary from one person to the next.

To measure your IPD,hold a ruler (with millimeter markings) on your forehead in front of a mirror, as close to your eyes as possible. Open one eye and line up the 0 mark on the center of your pupil. Now, close that eye and open the other, and the distance to the center of your other pupil should be your IPD.

It might be less obvious, but if you look closer at the VR screen, you will see color separations, like you'd get from a color printer whose print head is not aligned properly. This is intentional. Light passing through a lens is refracted at different angles based on the wavelength of the light. Again, the rendering software inverts the color separation so that it looks correct to us. This is referred to as a chromatic aberration correction. It helps make the image look really crisp.

The resolution of the screen is also important to get a convincing view. If it's too low res, you'll see the pixels, or what some refer to as a screen-door effect. The pixel width and height of the display is an oft-quoted specification when comparing the HMDs, but the pixels per inch (PPI) value may be more important. Other innovations in display technology, such as pixel smearing and foveated rendering (showing higher-resolution details exactly where the eyeball is looking) help improve the apparent resolution and reduce the screen-door effect.

When experiencing a 3D scene in VR, you must also consider the frames per second (FPS). If the FPS is too slow, the animation will look choppy. Things that affect FPS include the GPU performance and the complexity of the Unity scene (the number of polygons and lighting calculations), among other factors. This is compounded in VR because you need to draw the scene twice, once for each eye. Technology innovations, such as GPUs that are optimized for VR, frame interpolation, and other techniques, will improve the frame rates. For us developers, performance-tuning techniques in Unity that are often used by mobile game developers can be applied in VR (we will talk more about performance optimization in Chapter 13, Optimizing for Performance and Comfort). These techniques and optics help make the 3D scene appear realistic.

Sound is also very important—more important than many people realize. VR should be experienced while wearing stereo headphones. In fact, you can still have a great experience when the audio is done well but the graphics are pretty crappy. We see this a lot in TV and cinema. The same holds true in VR. Binaural audio gives each ear its own stereoviewof a sound source in such a way that your brain imagines its location in 3D space. True 3D audio provides an even more realistic spatial audio rendering, where sounds bounce off nearby walls and can be occluded by obstacles in the scene to enhance the first-person experience and realism.

For a fun example of binaural audio, put on your headphones and visit the classic Virtual Barber Shop at https://www.youtube.com/watch?v=IUDTlvagjJA. No special listening devices are needed. Regular headphones will work (speakers will not).

Lastly, the VR headset should fit your head and face comfortably so that it's easy to forget that you're wearing it, and it should block out light from the real environment around you.

Head, hand, and body tracking

So, we have a nice 3D picture that is viewable in a comfortable VR headset with a wide field of view. If we had this setup and you moved your head, it'd feel like you had a diorama box stuck to your face. Move your head and the box moves along with it, and this is much like holding the antique stereograph device or theView-Master. Fortunately, VR is so much better.

The VR headset has a motion sensor (IMU) inside that detects spatial acceleration and rotation rates on all three axes, providing what's called the six degrees of freedom (6DOF). This is the same technology that is commonly found in mobile phones and some console game controllers, but perhaps with higher sensitivity and accuracy. With the IMU integrated into your headset, when you move your head, the current viewpoint is calculated and used when the next frame's image is drawn. This is referred to as motion detection.

The previous generation of mobile motion sensors was good enough for us to play mobile games on a phone, but for VR, it's not accurate enough. These inaccuracies (rounding errors) accumulate over time, as the sensor is sampled thousands of times per second, and you may eventually lose track of where they were in the real world. This drift was a major shortfall of the older, phone-based Google Cardboard VR. It could sense your head's motion, but it lost track of your head's orientation. The current generation of phones, such as Google Pixel and Samsung Galaxy, which conform to the Daydream specifications, have upgraded sensors.

High-end HMDs account for drift with a separate positional tracking mechanism:

  • Inside out: The original Oculus Rift CV1 did this with inside-out positional tracking, where an array of (invisible) infrared LEDs on the HMD were read by an external optical sensor (infrared camera) to determine your position. You need to remain within the view of the camera for the head tracking to work.
  • Outside in: Alternatively, the Steam VR VIVE Lighthouse technology uses outside-in positional tracking, where two or more dumb laser emitters are placed in the room (much like the lasers in a barcode reader at the grocery checkout), and an optical sensor on the headset reads the rays to determine your position.
  • Spatial mapping: The Oculus Rift-S, Vive Cosmos, and Windows MR headsets use no external sensors or projectors. Rather, the headset itself contains all the integrated cameras and sensors needed to perform spatial mapping of the local environment around you in order to locate and track your position in real-world 3D space.

Either way, the primary purpose is to accurately find the position of your head and other similarly equipped devices, such as handheld controllers.

Together, the position, tilt, and forward direction of your head—or the head pose—are used by the graphics software to redraw the 3D scene from this vantage point. Graphics engines such as Unity are really good at this.

Now, let's say that the screen is getting updated at 90 FPS, and you're moving your head. The software determines the head pose, renders the 3D view, and draws it on the HMD screen. However, you're still moving your head, so by the time it's displayed, the image is a little out of date with respect to your current position. This is called latency, and it can make you feel nauseous.

Motion sickness caused by latency in VR occurs when you're moving your head and your brain expects the world around you to change exactly in sync. Any perceptible delay can make you uncomfortable, to say the least.

Latency can be measured as the time from reading a motion sensor to rendering the corresponding image, or the sensor-to-pixel delay. Oculus's John Carmack said the following:

A total latency of 50 milliseconds will feel responsive, but still noticeable laggy. 20 milliseconds or less will provide the minimum level of latency deemed acceptable.

There are a number of very clever strategies that can be used to implement latency compensation. The details are outside the scope of this book and inevitably will change as device manufacturers improve on the technology. One of these strategies is what Oculus calls the timewarp, which tries to guess where your head will be by the time the rendering is done and uses that future head pose instead of the actual detected one. All of this is handled in the SDK, so as a Unity developer, you do not have to deal with it directly.

Meanwhile, as VR developers, we need to be aware of latency as well as the other causes of motion sickness. Latency can be reduced via the faster rendering of each frame (keeping the recommended FPS). This can be achieved by discouraging your head from moving too quickly and using other techniques to make yourself feel grounded and comfortable. We talk more about comfort strategies in Chapter 7, Teleporting, Locomotion, and Comfort.

Another thing VR software does to improve head tracking and realism is use a skeletal representation of the neck so that all the rotations that it receives are mapped more accurately to the head rotation. For example, looking down at your lap creates a small forward translation since it knows it's impossible to rotate one's head downward on the spot.

Other than head tracking, stereography, and 3D audio, VR experiences can be enhanced with body tracking, hand tracking (and gesture recognition), locomotion tracking (for example, VR treadmills), and controllers with haptic feedback. The goal of all of this is to increase your sense of immersion and presence in the virtual world.

Technical skills that are important to VR

Being a VR developer requires the integration of multiple skills. Yes, you may likely specialize in one or a few areas. But sooner or later you're going to need at least some hands-on experience in a range of areas, as depicted in the following diagram:

Years ago, software development was revolutionized by the web. Web development draws upon a range of engineering and artistic disciplines to make a successful website, including artists, designers, typographers, photographers, and others. With VR, the reach is an order of magnitude greater. VR is multimedia, requiring audio, animation, and 3D design. VR is software engineering, requiring programming, debugging, and platform operations. VR is architecture and modeling, requiring 3D models, level design, and space construction. VR is theater and storytelling, requiring lighting, blocking, and character development. And the list goes on. But do not be discouraged. Consider this a challenge. Dip your toes into each aspect of the whole, and, as needed, deep dive into one area or another and engage friends and colleagues who have these skills and knowledge.

Each chapter of this book introduces new technical skills and concepts that are important if you wish to build your own VR applications. You will learn about the following in this book:

  • World scale: When building for a VR experience, attention to the 3D space and scale is important. One unit in Unity is usually equal to one meter in the virtual world.
  • First-person controls: There are various techniques that can be used to control the movement of your agent (first-person camera), gaze-based selection, tracked hand-input controllers, and head movements.

  • User interface controls: Unlike conventional video (and mobile) games, all user interface components are in world coordinates in VR, not screen coordinates. We'll explore ways to present notices, buttons, selectors, and other user interface (UI) controls to the users so that they can interact with the environment and make selections.
  • Lighting and rendering: Managing the look of each scene is important to accomplishing the feel you want. This is a complex set of topics (light sources, global illumination, render pipelines, quality settings, lightmapping, and other effects!). We'll introduce enough basics to get you going.
  • Physics and gravity: Critical to the sense of presence and immersion in VR is the physics and gravity of the world. We'll use the Unity physics engine to our advantage.
  • Animations: Moving objects within the scene is called animation—duh! It can either be along predefined paths or it may use artificial intelligence (AI) scripting that follows a logical algorithm in response to events in the environment.
  • Multiuser services: Real-time networking and multiuser games are not easy to implement, but online services make it easy without you having to be a computer engineer.
  • Build, run, and optimize: Different HMDs use different developer kits and assets to build applications that target a specific device. We'll consider techniques that let you use a single interface for multiple devices. Understanding the rendering pipeline and how to optimize performance is a critical skill for VR development.
  • C# programming: We will write scripts in the C# language and use features of Unity as and when they are needed to get things done.

However, there are technical areas that we will not cover. We will not go into modeling techniques, terrains, or humanoid animations. We also won't discuss game mechanics, dynamics, and strategies. All of these are very important topics that may be necessary for you (or for someone in your team) to learn, in addition to this book, to build complete, successful, and immersive VR applications.

So, let's see what this book actually covers and who it caters to.

What this book covers

This book takes a practical, project-based approach to teach the specifics of VR development using the Unity 3D game development engine. You'll learn how to use Unity 2020 to develop VR applications, which can be experienced with devices such as Oculus, Rift, Quest, HTC Vive, Cosmos, Valve Index, and even Google Cardboard.

However, we have a slight problem here—the technology is advancing very rapidly. Of course, this is a good problem to have. Actually, it's an awesome problem to have, unless you're a developer in the middle of a project or an author of a book on this technology! How does one write a book that doesn't have obsolete content the day it's published?

Throughout the book, I have tried to distill some universal principles that should outlive any short-term advances in VR technology, which include the following:

  • Categorization of different types of VR experiences with example projects
  • Important technical ideas and skills, especially those that are relevant to the building of VR applications
  • General explanations of how VR devices and software works
  • Strategies to ensure user comfort and and the avoidance of VR motion sickness
  • Instructions on using the Unity game engine to build VR experiences

Once VR becomes mainstream, many of these lessons will perhaps be obvious rather than obsolete, just like the explanations from the 1980s of how to use a mouse would just be silly today.

Who this book is for

If you are interested in VR, want to learn how it works, or want to create VR experiences yourself, then this book is for you. We will walk you through a series of hands-on projects, step-by-step tutorials, and in-depth discussions using the Unity 3D game engine.

Whether you're a nonprogrammer who is unfamiliar with 3D computer graphics or a person with experience in both, but who is new to VR, you will benefit from this book. It could be your first foray into Unity or you may have some experience, but you do not need to be an expert either. Still, if you're new to Unity, you can pick up this book as long as you realize that you'll need to adapt to the pace of the book.

Game developers may already be familiar with the concepts in the book, which are reapplied to the VR projects along with many other ideas that are specific to VR. Engineers and 3D designers may understand many of the 3D concepts, but they may wish to learn to use the Unity game engine for VR. Application developers may appreciate the potential nongaming uses of VR and want to learn the tools that can make this happen.

Whoever you are, we're going to turn you into a 3D software VR ninja. Well, OK, this may be a stretch for this little book, but we'll try to set you on the way.

Summary

In this chapter, we looked at virtual reality and realized that it can mean a lot of things to different people and can have different applications. There's no single definition, and it's a moving target. We are not alone, as everyone's still trying to figure it out. The fact is that VR is a new medium that will take years, if not decades, to reach its potential.

VR is not just for games; it can be a game-changer for many different applications. We identified over a dozen. There are different kinds of VR experiences, which we'll explore in the projects in this book.

VR headsets can be divided into those that require a separate processing unit (such as a desktop PC or a console) that runs with a powerful GPU and those that use mobile technologies for processing.

So, let's get to it! In the next chapter, we'll jump right into Unity and create our first 3D scene and learn about world coordinates, scaling, and importing 3D assets.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Unity 2020 Virtual Reality Projects - Third Edition
Published in: Jul 2020 Publisher: Packt ISBN-13: 9781839217333
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}