Reader small image

You're reading from  Unity Virtual Reality Projects

Product typeBook
Published inSep 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781783988556
Edition1st Edition
Languages
Right arrow
Author (1)
Jonathan Linowes
Jonathan Linowes
author image
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.
Read more about Jonathan Linowes

Right arrow

Chapter 7. Physics and the Environment

Parkour jumper: THOR/Parkour Foundations/Flickr, Creative Commons (source https://www.flickr.com/photos/geishaboy500/2911897958/in/album-72157607724308547/)

In the previous chapters, the first-person character was mostly limited to the X-Z ground plane. This chapter will focus more on the y-axis, as we explore adding physics to the virtual experience. You will see how properties and materials based on physics can be added to objects, as well as how one can transfer physical forces between objects using the C# scripting.

In this chapter, you will learn the following topics:

  • The Unity physics engine, the Unity Rigidbody component, and physic materials

  • Transferring physical forces from one object to another with scripting

  • Implementing velocity and gravity on first-person characters

  • Interacting with the environment, including headshots and jump gestures

  • Building models in Blender

Note that the projects in this chapter are separate and are not directly required...

Unity physics


In Unity, the behavior of an object that is based on physics is defined separately from its mesh (shape), materials (UV texture), and the renderer properties. The items that play into physics include the following:

  • The Rigidbody component

  • The Collider component

  • The Physic Material

  • The project Physics Manager

Basically, physics (in this context) is defined by the positional and rotational forces that affect the transform of an object, such as gravity, friction, momentum, and collisions with other objects. It is not necessarily a perfect simulation of physics in the real world because it's optimized for performance and separation of concerns to facilitate animation. Besides, virtual worlds might just need their own laws of physics that aren't found in our God-given universe!

Unity 5 integrates the NVIDIA PhysX engine, a real-time physics calculation middleware, which implements classical Newtonian mechanics for games and 3D applications. This multiplatform software is optimized...

Bouncy balls


Feature: When a ball drops from mid-air and hits the ground, it bounces back up and down, and up again, diminished by gravity.

We are going to start simply with a new scene that consists of a ground plane and a sphere. Then, we'll add physics to it, a bit at a time, as follows:

  1. Create a new scene by navigating to File | New Scene.

  2. Then, navigate to File | Save Scene As... and name it BallsFromHeaven.

  3. Create a new plane by navigating to GameObject | 3D Object | Plane and reset its position using the Transform component's gear icon | Reset.

  4. Create a new sphere by navigating to GameObject | 3D Object | Sphere and rename it BouncyBall.

  5. Set its Scale to (0.5, 0.5, 0.5) and Position to (0, 5,0) so that it's above the center of the plane.

  6. Drag the Red material from Project Assets (created in Chapter 2, Objects and Scale) onto it so that it looks like a bouncy ball.

The new Unity scene defaults come with Directional Light and Main Camera. It's OK to use this Main Camera for the time being...

Headshots


Wouldn't it be fun to actually play with these bouncy balls? Let's make a game – try to aim the ball at a target using headshots. For this game, balls drop one at a time from above and bounce off your forehead (face), aiming for a target.

Feature: When a ball drops from above your head, you bounce it off your face and aim for a target.

To implement this, place a cube collider on the MeMyselfEye head, parented by the VR camera, so our head pose will move the face of the cube. I decided a cube shaped collider will be better for this game than a sphere or capsule, because it provides a flat face (like a paddle) that will make the bounce direction more predictable. Balls will drop out of the sky. For a target, we'll use a flattened cylinder. We'll add audio cues to indicate when a new ball has been released, and when a ball hits the target.

Create a new scene and implement the head as follows:

  1. Navigate to File | Save Scene As and name it BallGame.

  2. Delete the BallsFromHeaven script component...

Trampoline and brick


A trampoline differs from a bouncy ball because the former makes things that collide with it bounce instead of itself bouncing. Unity doesn't do this automatically for us, So, we need to use scripting.

Feature: When a brick drops from mid-air onto a trampoline, it bounces up, diminished by gravity.

Build the scene and turn the target into a trampoline, as follows:

  1. Navigate to File | Save Scene As and name it BrickTrampoline.

  2. Delete the BallGame script component from GameController using gear icon | Remove Component. We won't need it.

  3. Rename the Target object to Trampoline.

  4. Set its Position to (0, 0.2, 0).

  5. To create the brick, navigate to GameObject | 3D Object | Cube and rename it to Brick.

  6. Set its Scale to (0.25, 0.5, 1) and Position to (0, 5, 0).

  7. Drag the Red material onto it.

  8. Add a Rigidbody by navigating to Add Component | Physics | Rigidbody.

When you play now, the brick drops to a dead stop. Make a new script on trampoline, as follows:

  1. With Trampoline selected in Hierarchy...

A human trampoline


Now, you'll get to jump on the trampoline yourself.

Feature: When a first-person character hits a trampoline, it bounces up, diminished by gravity.

Like a brick

One approach towards implementing this feature could be to treat the MeMyselfEye first-person character like Brick and give it a Rigidbody and a Capsule Collider so that it can respond using physics. We'll try this first just to see whether it works. For this to work, we need to disable its Character Controller component and start at the brick's position above the trampoline so that we can just drop, as follows:

  1. Navigate to File | Save Scene As and name it HumanTrampoline.

  2. Delete Brick in Hierarchy; we won't need it.

  3. With MeMyselfEye selected in Hierarchy, set Position to (0, 5, 0).

  4. Navigate to Add Component | Physics | Rigidbody.

  5. Navigate to Add Component | Physics | Capsule Collider and set its Height to 2.

  6. In the Rigidbody panel, under Constraints, check off the Freeze Rotation X, Y, Z checkboxes so that we don't get...

Interlude – environment and things


Let's spice up the scene with some more interesting environment and geometry. This section is optional. You can follow along or even do your own thing.

I've provided assets in the download files associated with this book. Where mentioned in the following section, some of these may be a part of the free packages found in the Unity Asset Store and included with permission from the creators:

  1. Start a new version of the scene, save it navigating to File | Save Scene As..., and name it PhysicsWorld.

  2. Select the ground plane and change its Scale to (5, 1, 5).

Now, we'll add some sky and earth.

Wispy Sky

We will add a nicer skybox named Wispy Sky. To add the skybox, perform the following steps:

  1. Import the assets package provided with this book named WispySky.package.

  2. From the main menu bar, navigate to Window | Lighting.

  3. In the Lighting panel, select the Scene tab.

  4. In the Skybox field, click on the circle icon on the far right to open the Select Material dialog box.

  5. Select...

An elevator


Want to see the view from the top of the logo? Let's make a Mario-style elevator to get there.

Feature: Provide an elevator platform, which moves up and down, that I can walk onto and ride to the top of my logo.

Build it into the scene by performing the following steps:

  1. Create the elevator platform by navigating to GameObject | 3D Object | Cube. Name it Elevator.

  2. Set its so that it's aligned with the logo. By doing this, you can ride the platform and walk off it onto the top of the logo. I set Position to (17, 1.4, -8.8) and Scale to (4, 0.1, 4).

  3. Drag the Blue material onto it.

  4. Create the script by navigating to Add Component | New Script. Name it Elevate and open it for editing.

Here's the Elevate.cs code:

using UnityEngine;
using System.Collections;

public class Elevator : MonoBehaviour {
  public float minHeight = 1.2f;
  public float maxHeight = 8.0f;
  public float velocity = 1;
  
  void Update () {
    float y = transform.position.y;
    y += velocity * Time.deltaTime;
   ...

Jumping


When we created the trampoline, I mentioned that our implementation doesn't require you to jump to start bouncing. However, jumping is a fun idea, whether on a trampoline or not. Some games use the keyboard spacebar or a controller button to make your avatar jump. We'll now implement a simple jump gesture from the VR headset, which applies a vertical velocity to our movement.

Note

Note that this will not work with headsets that lack positional tracking, such as Google Cardboard and GearVR.

Feature: When I jump, my character in VR jumps.

To implement a jump gesture, we'll look for a rapid change in the Y position of the headset, which is very similar to the head nod gesture that we did in Chapter 5, World Space UI, (which checked for a rapid change in the x-axis angle). When a jump gesture is detected, we'll apply a vertical force to the first-person , as follows:

  1. With MeMyselfEye selected in Hierarchy, create the script by navigating to Add Component | New Script.

  2. Name it JumpGesture...

Summary


In this chapter, we took a grand tour of Unity's physics engine. First, I explained in layman's terms the relationship between Rigidbody, Colliders, and Physic Materials, and how the physics engine uses these to determine the velocity and collision of objects in the scene.

Then, we went through a variety of examples that showed how one can use the physics engine directly, indirectly, and not at all. The bouncy balls used the engine without scripting, but then we wrote scripts on top of it to implement a headshot game and a shower of balls. The trampoline examples use the physics engine to detect collisions, and we scripted the transfer force to another object. Lastly, we implemented our own gravity and bounce forces on a first-person character, including a jump gesture. We did all of this while orbiting the Earth! Wonders never cease!

Physics mechanics are very important in game design as well as virtual reality. Unity's robust physics API gives developers the tools that are required...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Virtual Reality Projects
Published in: Sep 2015Publisher: PacktISBN-13: 9781783988556
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.
undefined
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

Author (1)

author image
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.
Read more about Jonathan Linowes