Как получить данные от контроллера при использовании системы взаимодействия SteamVR

Я хочу просто получить ввод контроллера от пользователя в моей игре VR, и я также хочу использовать систему взаимодействия SteamVR, чтобы я мог легко реализовать элементы пользовательского интерфейса. Однако я не могу получить входные данные от контроллера из сценария Hand.

Все, что я сделал, - это перетащил префаб «Player», а затем написал сценарий для перехода к объекту Hand для получения входных данных от триггеров.

    private Hand _hand;                     // The hand object
    private SteamVR_Controller.Device controller; // the controller property of the hand


    void Start ()
    {
        // Get the hand componenet
        _hand = GetComponent<Hand>();
        // Set the controller reference
        controller = _hand.controller;
    }

    void Update ()
    {
            // === NULL REFERENCE === //
        if ( controller.GetHairTrigger())
        {
            Debug.Log ("Trigger");
        }

    }

Это дает мне исключение null ref для объекта «контроллер». Я также пробовал установить компонент контроллера в OnEnable() и Awake(), но это тоже не сработало. Даже в Update(). Поэтому по какой-то причине класс Hand SteamVR не содержит ссылки на контроллер. Я что-то делаю не так? Мне не хватает какой-то спецификации индекса, когда я получаю контроллер?

Я могу получить ввод от контроллера следующим образом:

   private SteamVR_TrackedObject trackedObj;       // The tracked object that is the controller

    private SteamVR_Controller.Device Controller    // The device property that is the controller, so that we can tell what index we are on
    {
        get { return SteamVR_Controller.Input((int)trackedObj.index); }
    }

    private void Awake()
    {
        // Get the tracked object componenet
        trackedObj = GetComponent<SteamVR_TrackedObject>();
    }

    void Update()
 {
     if(Controller.GetHairTrigger()){
          Debug.Log("hey trigger");
     }
  }

Но тогда я не могу использовать систему взаимодействия. У кого-нибудь есть подсказка?


person BenjaFriend    schedule 20.04.2017    source источник


Ответы (3)


Я действительно предлагаю вам добавить бесплатный HTC.UnityPlugin от Valve в вершина интеграции SteamVR, поэтому вы можете быстро получить доступ к вводу контроллеров с помощью

using UnityEngine;
using HTC.UnityPlugin.Vive;
public class YourClass : MonoBehaviour
{
    private void Update()
    {
        // get trigger
        if (ViveInput.GetPressDown(HandRole.RightHand, ControllerButton.Trigger))
        {
            // ...
        }
    }
}
person Omar Guendeli    schedule 27.04.2017

Не устанавливая никаких дополнительных зависимостей, кроме SteamVR, прикрепите скрипт к одному из Hand компонентов. Это дочерний элемент префаба Player в папке ресурсов SteamVR.

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

public class Grab: MonoBehaviour {
    private Valve.VR.InteractionSystem.Hand hand;

    void Start () {
        hand = gameObject.GetComponent<Valve.VR.InteractionSystem.Hand>();
    }

    void Update () {
        if (hand.controller == null) return;

        // Change the ButtonMask to access other inputs
        if (hand.controller.GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
        {
            Debug.Log("Trigger down")
        }

        if (hand.controller.GetPress(SteamVR_Controller.ButtonMask.Trigger))
        {
            Debug.Log("Trigger still down")
        }

        if (hand.controller.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
        {
            Debug.Log("Trigger released")
        }
    }
}
person Mastergalen    schedule 03.12.2017
comment
Это больше не работает в текущем плагине Steam для Unity - под рукой нет свойства контроллера. Может ли кто-нибудь предложить правильный путь в настоящее время? Мне трудно читать вводы контроллера с новой системой. - person David Mennenoh; 12.10.2018
comment
Я использую этот способ: Firs: using Valve.VR.InteractionSystem; тогда вы можете получить доступ к таким раздачам: void Update () {foreach (var hand in Player.instance.hands) {... Надеюсь, это поможет - person qant; 10.07.2020

Вот как можно работать руками:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Valve.VR.InteractionSystem;

    public class ShowControllers : MonoBehaviour
    {
        public bool showController = false;
    
    // Update is called once per frame
    void Update()
        {
            foreach (var hand in Player.instance.hands)
            {
                if (showController)
                {
                    hand.ShowController();
                    hand.SetSkeletonRangeOfMotion(Valve.VR.EVRSkeletalMotionRange.WithController);
                }
                else
                {
                    hand.HideController();
                hand.SetSkeletonRangeOfMotion(Valve.VR.EVRSkeletalMotionRange.WithoutController);
            }
            }
        }
    }
person qant    schedule 10.07.2020