Средство 3D-просмотра отдельных объектов для Google Cardboard с Unity 5

Я пытаюсь воссоздать функциональность демо-версии «Exhibit» приложения Google Cardboard. т. е. просмотр одного объекта со всех сторон - посмотрите вверх и вы видите под объектом, посмотрите вниз и вы увидите его сверху, посмотрите влево или вправо и вы увидите его сбоку, затем сзади.

Я пробовал несколько вещей, таких как создание объекта дочерним элементом камеры и использование transform.LookAt(target);, чтобы камера сфокусировалась на объекте, но это не работает.

Новичок в Unity5, поэтому любая помощь будет очень признательна.


ОБНОВЛЕНИЕ

Используя код из скрипта SmoothMouseLook (http://pastebin.com/vMFkZJAm), это самое близкое, что у меня есть до сих пор, но на самом деле это не работает и кажется слишком «вышедшим из-под контроля» (объект продолжает вращаться, а не плавно поворачиваться для осмотра) и гораздо менее предсказуем, чем демонстрация «Exhibit». Я предполагаю, что я слишком усложняю вещи. Есть у кого идеи?...

На камерах («Основная камера») прикрепите это, чтобы сосредоточиться на объекте:

 using UnityEngine;
 using System.Collections;

 public class LookAt : MonoBehaviour {
     public Transform target;

     void Update () {
         transform.LookAt(target);
     }
 }

К объекту прикрепите этот скрипт:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class SmoothMouseLook : MonoBehaviour
{   
    /*
     This script is used to average the mouse input over x 
     amount of frames in order to create a smooth mouselook.
     */

    //Mouse look sensitivity    
    public float sensitivityX = 1f;
    public float sensitivityY = 1f;


    //Default mouse sensitivity
    public float defaultSensX = 1f;
    public float defaultSensY = 1f;


    //Minimum angle you can look up
    public float minimumY = -60f;
    public float maximumY = 60f;

    //Minimum angle you can look up
    public float minimumX = -60f;
    public float maximumX = 60f;


    //Number of frames to be averaged, used for smoothing mouselook
    public int frameCounterX = 35;
    public int frameCounterY = 35;


    //Mouse rotation input
    private float rotationX = 0f;
    private float rotationY = 0f;


    //Used to calculate the rotation of this object
    private Quaternion xQuaternion;
    private Quaternion yQuaternion;
    private Quaternion originalRotation;


    //Array of rotations to be averaged
    private List<float> rotArrayX = new List<float> ();
    private List<float> rotArrayY = new List<float> ();


    void Start ()
    {
        //Lock/Hide cursor

        if (GetComponent<Rigidbody>())      
            GetComponent<Rigidbody>().freezeRotation = true;


        originalRotation = transform.localRotation;

    }


    void FixedUpdate () 
    {

        //Mouse/Camera Movement Smoothing:    
        //Average rotationX for smooth mouselook

        float rotAverageX = 0f;
        //rotationX += Camera.main.transform.eulerAngles.x * sensitivityX;
        //rotationX += Cardboard.SDK.HeadRotation.eulerAngles.x * sensitivityX;
        rotationX += Cardboard.SDK.HeadPose.Orientation.x * sensitivityX;

        rotationX = ClampAngle (rotationX, minimumX, maximumX);

        //Add the current rotation to the array, at the last position
        rotArrayX.Add (rotationX);

        //Reached max number of steps?  Remove the oldest rotation from the array
        if (rotArrayX.Count >= frameCounterX) {

            rotArrayX.RemoveAt (0);

        }

        //Add all of these rotations together
        for (int i_counterX = 0; i_counterX < rotArrayX.Count; i_counterX++) {
            //Loop through the array
            rotAverageX += rotArrayX[i_counterX];
        }


        //Now divide by the number of rotations by the number of elements to get the average
        rotAverageX /= rotArrayX.Count;


        //Average rotationY, same process as above
        float rotAverageY = 0;
        //rotationY += Camera.main.transform.eulerAngles.y * sensitivityY;
        //rotationY += Cardboard.SDK.HeadRotation.eulerAngles.y * sensitivityY;
        rotationY += Cardboard.SDK.HeadPose.Orientation.y * sensitivityY;

        rotationY = ClampAngle (rotationY, minimumY, maximumY);
        rotArrayY.Add (rotationY);


        if (rotArrayY.Count >= frameCounterY) {
            rotArrayY.RemoveAt (0);
        }


        for (int i_counterY = 0; i_counterY < rotArrayY.Count; i_counterY++) {  
            rotAverageY += rotArrayY[i_counterY];
        }


        rotAverageY /= rotArrayY.Count;


        //Apply and rotate this object
        xQuaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
        yQuaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);

        transform.localRotation = originalRotation * xQuaternion * yQuaternion;

    }



    private float ClampAngle (float angle, float min, float max)
    {
        if (angle < -360f)  
            angle += 360f;
        if (angle > 360f)
            angle -= 360f;

        return Mathf.Clamp (angle, min, max);

    }
}

person baroquedub    schedule 01.09.2015    source источник


Ответы (1)


Для этого конкретного случая использования вам не нужен сценарий. Предполагая, что вы используете префаб CardboardMain, сделайте следующее:

  • Поместите объект в начало координат и туда же CardboardMain.
  • В настройках картона установите Масштаб модели шеи на 0.
  • Откройте CardboardMain и выберите Main Camera под объектом Head.
  • Установите значение Transform Position Z на отрицательное значение (достаточно далеко, чтобы увидеть объект).

(Вы можете думать об этом как о модели камеры «палка для селфи».)

person smd    schedule 01.09.2015
comment
Отличный материал. Я знал, что слишком все усложняю! Ради интереса, где вы узнали о модели шеи и других настройках Cardboard в Unity? Только начал и нашел только основные документы SDK (в которых отсутствуют примеры) и ничего больше. - person baroquedub; 01.09.2015
comment
Что ж, я немного схитрил — помог написать SDK :-) Вы правы, документация по-прежнему минимальна. - person smd; 02.09.2015
comment
Спасибо @smd Есть идеи, как добавить инерцию к вращению объектов, чтобы они медленно останавливались, когда вы перестаете двигать головой? - person robflate; 30.09.2015