Unity Gaming: Integrating Oculus

Setting Up

GREAT NEWS! In 2015 you no longer need Unity Pro Edition to integrate Oculus into your projects. YAY!

Things you’ll need for integration:

  • An Oculus (really you don’t need one to develop but how else will you test it out?)
  • Oculus SDK
  • Oculus Runtime
  • Unity 4 Integration

Okay so, the first thing you’ll need is to have your game all set up and running, in Unity. If you’ve been following my blog then you should have the bulk of the game running.

Cool. Next we need to grab the Oculus pieces from their site.

https://developer.oculus.com/downloads/

Now if you have a Mac or Linux download from those links.

WebsiteDownloads

 

After you download the links you now need to install the runtime. Then restart your computer.

Integrating into Unity

Extract the files from the Unity Integration Package you downloaded. Go Into Unity to Assets>Import Package> Custom Package

Find where you extracted the files and navigate to the Unity Plugin.

ImportingPackage2

 

Then hit import.

ImportingPackage3

Now you should have a new folder in your Assets called OVR

AssetsOVR

Cool so now it’s integrated lets Start using the Oculus Camera in the game.

Using Oculus Cameras

Now using the Oculus Package is super easy. Oculus has already created prefabs for developers to use. They have a prefab with just the camera rig as well as one with the rig and a character motor.

OVRPrefabs

To use them. Just do what you what you would normally do with prefabs. Click and Drag it into your scene.  I created a test scene called OVRTest to make sure everything would work without worrying about the infinite platforms generating around me.

I placed the OVRPlayerController at 0, 2, 0.

OVRinScene

Cool Now try running the game. You should have something that looks like this:

OVRGame

 

YAY! See super easy. The double circle screen is what will be fed to your Oculus, and with the lenses and the headset it should become one image with a 3 dimensional feel.

Now that you have the basic character installed you can add it to the main game scene and try it with the infinite platforms.

 

Happy Coding!

-TheNappingKat

Unity Gaming: Rotation

Quaternions

In Unity Rotations are stored as Quaternions. Quaternions work like vectors but their coordinates of x, y, z, and w are interdependent. These are different from the Euler angle rotation that you see in the inspector.

Because quaternion coordinates are interdependent you should never change them individually as you might when placing objects in the world initially. The reason Quaternions are the preferred method for rotating is because they allow for incremental rotation, without being subject to gimbal lock, which sometimes locks objects in 2D rotation when you need 3 dimensions.

There are 4 main quaternion functions used for rotation; AngleAxis, RotateTowards, LookRotation, and FromToRoatation.
To create the world gravity shift we rotate the platforms around the character.

Rotating platforms

Okay so for the rotation and Flipping in the game we need a rotation object that has the platforms as children.

  1. Create a empty object
  2. Rename it PlatformRotator
  3. Move the object to 0,0,0
  4. In the hierarchy move the platforms and the platform spawner controller that we made earlier into the PlatformRotator to parent it

Great, now for the hard part. It took me several weeks to get this rotation to go a perfect 90 with each flip as well as 180 degrees. In this game we want the user to  press a key have the rotation go without use needing to hold down the key or press it a bunch of times. We could make it happen instantly, but for VR and UX purposes we don’t want to do that either. Now many beginner tutorials won’t explain how to do this. The answer is coroutines. Coroutines allow the rotation method to execute multiple times as it gives back control to other parts of the game.

The other difficult part finding which of the quaternion functions to use and how do you rotate spawned objects. Okay, so with that said lets start with the quaternion function we want to use and how to apply it to all my platforms.

Rotation Script

This rotation script will be attached to our PlatformRotator. What we want to do is get user input, see if the platforms are rotating, and if they aren’t, start the rotation.

Lets add a boolean to see if the platforms are rotating and a float to keep the degree of the angle we want to go to.

private bool rotating; 
private float angle = 0.0f; 

So to get user input we need to write the following inside the Update function.

void Update () {
	if(Input.GetKeyUp(KeyCode.Q)){
		
		if(!rotating) {
			
		}
	}

	if(Input.GetKeyUp(KeyCode.E)){
			
		if(!rotating) {
			
		}
	}

	if(Input.GetKeyUp("space")){
			
		if(!rotating) {
			
		}
	}
}

We also need to calculate the angle of exact rotation. In order to do a smooth rotation we will be adding and subtracting 90 degrees from the current angle, and restarting if it gets back to zero.

	float getNextLeftAngle (float oAngle){
		oAngle = oAngle + 90; 
		return oAngle; 
	}

	float getNextFlip (float oAngle)
	{
		oAngle = oAngle + 180; 
		return oAngle; 
	}
	
	float getNextRightAngle (float oAngle)
	{
		oAngle = oAngle - 90; 
		return oAngle; 
	}

Now we use the angles to pass into the coroutines. Every coroutine is an IEnumertor function. Which means we need to import the System.Collections library.

We need two coroutines, one for rotating, one for flipping. The coroutine works by having a while loop that returns yield return null. Yield return null tells the engine that when you reach this method again, start from the while loop.

	IEnumerator FlipMe (float nextstep)
	{
		rotating = true; 
		float step = 232 * Time.smoothDeltaTime;
		Quaternion fromAngle = transform.rotation;
		Quaternion newRotation = Quaternion.Euler (new Vector3(0, 0, nextstep));	

		while (transform.rotation != newRotation) {//the original angle from the input key dot with 90 degree < !=  0 
			transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, step);
				yield return null;
		}
		rotating = false; 			
	}

I use the rotate towards quaternion function because we have a goal angle that we get closer to each time we run the coroutine.
We do the same for the Rotate coroutine. I have two methods because the step aka speed of rotation. I wanted the rotation to be slightly faster than flipping because in VR a full 180 degree flip is slightly more jarring, so slower speed is needed.

IEnumerator RotateMe(float nextstep) {
		rotating = true; 
		float step = 500 * Time.smoothDeltaTime;
		Quaternion fromAngle = transform.rotation;
		Quaternion newRotation = Quaternion.Euler (new Vector3(0, 0, nextstep));	
		while(transform.rotation != newRotation){//the original angle from the input key dot with 90 degree < !=  0 
			transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, step);//newRotation;
			yield return null;

		}
		rotating = false; 
	}

Now we need to call the coroutine in the Update function:

	void Update () {
		if(Input.GetKeyUp(KeyCode.Q)){
		
			if(!rotating) {
				angle = getNextLeftAngle(angle);
				StartCoroutine(RotateMe(angle));
			}
		}

		if(Input.GetKeyUp(KeyCode.E)){
			
			if(!rotating) {
				angle = getNextRightAngle(angle);
				StartCoroutine(RotateMe(angle));
			}
		}

		if(Input.GetKeyUp("space")){
			
			if(!rotating) {
				angle = getNextFlip(angle); 
				StartCoroutine(FlipMe(angle));
			}
		}
	}

Now we add this script to the PlatformRotator Object. Run the code and now we see that each time we hit ‘q’, ‘e’, or ‘space’ the platfroms rotate appropriately. YAY!

Okay and now we are done with the biggest chunk of the game! Really all that’s left is adding game mechanics like ending the game and getting points.

Happy Coding!

-TheNappingKat

Unity Gaming: Getting Infinite Working

Infinite Runner

Okay so the game I’m making is an infinite runner. What’s an infinite runner. Well it’s pretty self-explanatory but just to make sure everyone is on the same page; an infinite runner game is a game where the world is procedurally generated as the player experiences it, and will exist for as long as the player is alive. Most infinite runners take the title seriously and have their players running along a path that is never ending while collecting prizes and/or dodging enemies.

This unique-ish twist that this example has, is that it’s not going to be 3rd person or 2D like most infinite runner.

Gravity Gunner is a First Person Shooter Infinite Runner.

Platforms

So for our infinite runner we need a character to run constantly. Now you can do this of two ways.

  1. Have the user control your charters speed and movement. While the environment passes by. Think Super Mario Bros.
  2. The player’s speed/position is locked and the user can only control limited direction. Think Temple Run.

In this example the player’s forward direction is locked and the user can only manipulate left/right direction. 

Spawners

Understanding Spawners

Okay so when I say Spawner, what do I mean. Well the Spawner is an object that generates objects, either from scratch or clones of specified objects. In an infinite runner the Spawner refers to the script that will generate the next platform in your series. Now we will use Spawners for our platform generation but it can also be used for generating enemies.

So before we can create our Spawner we should create the objects that we want to Spawn and convert to Prefabs. This way the prebas can be used multiple times in our game.

For an infinite runner I want to create flat platforms for my character to run on. And since the character is going to manipulate “gravity” we will want to spawn four platforms to form a hallway with top, bottom, left and right sides.

So for this piece let’s start simple and build from there.

With any infinite runner its all about the prefabs. The Platform prefabs usually contain.

  • The model for the platform
  • The behavior of that platform, a.k.a whether or not it’s moving
  • Enemy characters
  • Coins or items for the characters
  • Random other triggers for end of level, or game actions

Although some of the items will be generated randomly by their own spawners the location of them in the world usually is dependent on the world/pieces/platforms generated.

Creating Span Object/Platform

So I’m creating my own platform, but you can easily import one from the assets store or from a 3D modeling program. I’m just doing it this way cause it’s faster.

  1.  Create a Cube
    • Make sure it’s at 0, 0, 0
    • I like the dimensions to be 6, 1, 14
  2. Create Prefab
    • It’s really important to maintain organization when building a game. Your Assets folder can become unmanageable really quickly if you don’t have any organization. I’ll talk about it in a later post, but for now trust me. MAKE FOLDERS! I create folders based on the items in my game. For example usually I’ll have a folder for MyPrefabs, MyAudio, MyMaterial, MyScenes, and MyScripts. So in Assets you Should Create a folder called “MyPrefabs”  and to that folder Create a prefab called “SimplePlatform”.
    • Drag Cube Object from the Hierarchy to the Prefab.
  3. Create the Spawner Object
    • Create an Empty Object, Place it at 0, 0, 0.
    • Rename it Spawner.

Okay now let’s make the Spawner do something.

Spawner Script

    1.  Create List
      • This is for keeping track of your objects in case you need to do manipulation to your objects. You know like destroying them, or rotating them…
public List platformList;
public List platformTypes;
    1. Instantiate Platform
      • Now in your Start() method add the following
for(int i = 0; i < 6; i++){
    GameObject x = (GameObject)GameObject.Instantiate (this.PathPlatforms [0], new Vector3 (0, -3f, 0), Quaternion.identity);
    x.tag = bottomPlatformTag;
    x.gameObject.tag = "Platform";
    this.activeBottomPlatforms.Add (x);
}

Destoryers

Understanding Destoryers

So if the spawner and world are the heart of an infinite runner. The destroyer is the ventricles or something, trying to keep this analogy but I might end up switching, we’ll see.
Memory management, especially in games, is the main contributor to glitches and lag. Destoryers help with this by eliminating unnecessary objects from the scene that the engine no longer has to keep track of.

Destoryers and Spawners

Okay so there are many ways to make an infinite runner. I’ll explain one, and then tell you another way.
In ours, the Destoryer works with the Spawner and destroys platforms that are no longer necessary. Instead of having the Spawner spawn platform after platform after platform, we only spawn a set number in order to reduce the number of objects in memory. The destruction of a platform by the Destoryer triggers the Spawner to create another platform. And that’s how we get the “infinite” part of our infinite runner. =D
Although there are other ways to implement the infinite runner, they all consist of some sort of spawner and destroyer. Some Spawners are timed based and will generate platforms based on how much time has gone by, but the destroyer will still exist and destroy objects as they leave the screen.

Creating Destoryers

Create the Destroyer Object by:

  1. Making a cube
  2. Move the cube back to the -20 in the z axis
  3. Scale it to 10x10x1 in the x, y , and z plane
  4. Then take away it’s mesh render

Okay, so now that’s it’s created let’s make it destory the platforms

Destoryer Script

Create another script in the MyScripts folder called “DestoryerBehavior”.
Then add a OnTriggerEnter() method so the Destoryer can be triggered by the objects it intersects. In the Ontrigger add an if statement to check and see if the object setting off the trigger is a platform. If it is, destory it.

    void OnTriggerEnter(Collider other) {

        string collideTag = other.tag;

        if (collideTag == "Platform")
        {
            Destory(other.gameObject);
        }

    }

See super simple. However, we still need to get the Spawner and the Destoryer to work together

Putting it Together

There are two tasks left to complete, 1) Getting the platforms to run into the Destoryer 2) Getting the Destoryer to signal the Spawner to create a new platform.

Moving Platforms

To get the Platforms to collide with the Destoryer we need to add script to the platform prefab that will move the platforms backwards towards the Destroyer.
So on the SimplePlatform Prefab add a new component in the inspector. Create a C# Script called “MoveBackwards”. In it add this script to the update function as well a float for the speed.

    public float backspeed = 3.0f;

    
    // Update is called once per frame
    void Update () {
        transform.Translate(Vector3.back * Time.deltaTime * backspeed);
        }

Script Interction

So to interact with the Spawner the DestoryerBehavior needs to reference the Spawner’s Script. We can do this by Finding the appropriate object and then getting the component we want from the object. Add these fields to the DestroyerBehavior:

    public float backspeed = 3.0f;

    
    // Update is called once per frame
    void Update () {
        transform.Translate(Vector3.back * Time.deltaTime * backspeed);
        }

Now we want to remove the platform the Destoryer collided with from the Spawner’s list, as well as Destory the object.
To do that we need to edit the Destoryer’s OnTriggerEnter method.

        if (collideTag == "Platform")
        {
            
        platformControllerScript.activeRightPlatforms.Remove(other.gameObject);
        Destroy(other.gameObject);

Great so now the Spawner will be automatically triggered to spawn a new Platform.
Run your scene and you should see the platforms being destroyed and spawned so that there are always six. =D

And there you have it. Infinite is now working in your game!
Happy Coding!

-TheNappingKat