Kitten VR начинался как эксперимент по созданию низкополигональных сред в Unity 5 и быстро превратился в простое приложение с большим потенциалом. Мои цели с Kitten VR двояки: иметь простую, удобную мини-игру для использования с устройствами виртуальной реальности, которую я могу использовать в качестве основы для тестирования новых VR SDK, и задокументировать процесс для тех, кто заинтересован в изучении того, как создавать приложения, которые сами используют преимущества современной экосистемы виртуальной реальности.

Сейчас я использую Oculus Runtime 0.5.1 и плагин Unity для 0.4.4 (более новые версии плохо работают с Unity 5, поэтому пока импровизирую). Я надеюсь, что скоро будут доступны загружаемые версии!

Для получения подробной информации о том, что я строю, читайте дальше!

Окружающая среда
На данный момент Kitten VR представляет собой одноэтапное приложение, в котором пользователь помогает кошке найти всех 7 пропавших без вести котят. Среда представляет собой сцену Unity, созданную с помощью простого элемента Terrain и игрового объекта Plane, оба из которых имеют яркие цвета и текстуры из пакета активов Cartoon Forest Environment, который можно приобрести в магазине активов.

Персонажи
В сцене спрятано 7 коллекционных котят, которые представляют собой анимированные заготовки из бесплатного пакета Kitten. Еще один котенок — это базовый персонаж NPC, который сообщает пользователю его цель и не может быть собран. Существует также контроллер персонажа, который использует префаб FPS Character Controller с Oculus Camera Rig, заменяющим обычную камеру.

KittenController.cs
Пользователь может получить подсказку об общем игровом процессе, щелкнув ближайшего котенка в точке появления. У этого котенка есть компонент сценария KittenController, написанный на C#, который определяет поведение OnClick и отображает сообщение в зависимости от того, сколько котят было найдено. Сценарий использует `RaycastHit` и `Ray`, чтобы определить, был ли щелчок на цели котенка. Если игрок не подобрал ни одного из них, ведущий котенок сообщит игроку о своей миссии. В противном случае котенок будет отображать, сколько еще кошек нужно найти. После того, как все котята будут обнаружены, игра перезагрузится после того, как игрок щелкнет родительского котенка.

using UnityEngine;
 using System.Collections;
 
public class KittenController : MonoBehaviour {
 public bool isVisible = false;
 private float timer = 0.0f;
 public PlayerController playerStats;
 private string message;
 
// Use this for initialization
 void Start () {}
// Update is called once per frame
 void Update () {
 if (Input.GetMouseButtonDown (0)) {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit))
     if (hit.transform != null) {
      if (hit.transform.gameObject == this.gameObject) {if(playerStats.kittens_collected == 0)
 {
 message = "Help! My kittens have gone missing! Can you help collect all 7 of them?";
 isVisible = true;
 }
 else if(playerStats.kittens_collected == 1)
 {
 message = "You've found one kitten so far! Just 6 more to go!";
 isVisible = true;
 }
 else if(playerStats.kittens_collected < 7)
 {
 message = "You've found " + playerStats.kittens_collected + " kittens so far! Just " + (7 - playerStats.kittens_collected) + " left to go!";
 isVisible = true;
 }
 else
 {
 message = "You've found them all! Thank you so meouch!";
 isVisible = true;
 System.Threading.Thread.Sleep(2000);
 Application.LoadLevel(Application.loadedLevel);
 }}}}
 if (isVisible) {
 timer++;
 }
 if (timer > 300f) {
 isVisible = false;
 timer = 0f;
 }}
void OnGUI()
 {
   if (isVisible) {GUI.Box (new Rect (Screen.width / 2 - 290, Screen.height / 1 - 100, 600, 80), message);
  }
 }
}
PlayerController.cs
PlayerController.cs is another C# script attached to the player to track the number of kittens that the player has found. It has two functions that are called in the `Update()` method: `CheckPosition()` and `MouseClickListener()` The first method checks to make sure the user hasn't jumped off the game board (if so, the level will reset with the `Application.LoadLevel(Application.loadedLevel);` call) and the second uses another `RaycastHit` to see if a kitten has been touched. If so, the kitten is removed from the scene and added to the player's basic 'inventory'.
using UnityEngine;
 using System.Collections;
public class PlayerController : MonoBehaviour {
public int kittens_collected = 0;
 /**
 * Use this for initialization
 **/
 void Start () {}
/**
 * Update is called once per frame.
 * Check for various game play components.
 **/
 void Update () {
 MouseClickListener ();
 CheckPosition ();
 }
/**
 * Check and see if the user has jumped off of the level.
 * If so, reset the level.
 **/
 void CheckPosition()
 {
 if (this.gameObject.transform.position.y < 0) {
 Application.LoadLevel(Application.loadedLevel);
 }
 }
/**
 * A function to check if the player has clicked on a kitten.
 * Eventually update this with a different, more interactive input type.
 **/
 void MouseClickListener()
 {
 if (Input.GetMouseButtonDown(0)) {
 RaycastHit hit;
 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if (Physics.Raycast(ray, out hit))
 if (hit.transform != null) {
 if(hit.transform.gameObject.tag == "kitten")
 {
 kittens_collected++;
 Destroy(hit.transform.transform.gameObject);
 Debug.Log("You've collected " + kittens_collected + " kittens!");
 }}}}
}
The full code can be found on GitHub here. This is a living application and will have changes updated regularly with new features and functionality.
Interested in learning more, but unsure of where to start? Go from zero to application with my notes on building your first game from scratch with Unity 5!