// Start is called before the first frame update
        void Start()
        {
            List <InputDevice> devices = new List <InputDevice>();

            InputDevices.GetDevices(devices);

            foreach (var item in devices)
            {
                Debug.Log(item.name + item.characteristics);
            }
            // start the ROS connection
            ros = ROSConnection.instance;

            DateTime foo = DateTime.Now;

            restartTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();

            // Set up a subscriber to listen to commands
            ROSConnection.instance.Subscribe <JointPositions>("joint_commands", executeCommand);

            //
            ROSConnection.instance.Subscribe <AchievedGoal>("reset_environment", resetEnvironment);


            // Set up the arm variables
            this.gameObject.AddComponent <FKRobot>();
            articulationChain = this.GetComponentsInChildren <ArticulationBody>(); // https://docs.unity3d.com/2020.1/Documentation/ScriptReference/ArticulationBody.html?_ga=2.54684075.1087433992.1613790814-228562203.1613145667
            int defDyanmicVal = 10;

            foreach (ArticulationBody joint in articulationChain)
            {
                // Set up each of the joints
                joint.gameObject.AddComponent <JointControl>();
                joint.jointFriction  = defDyanmicVal;
                joint.angularDamping = defDyanmicVal;
                ArticulationDrive currentDrive = joint.xDrive;
                currentDrive.forceLimit = 10;
                joint.xDrive            = currentDrive;
                print(joint);
            }
            EngageForceAfterInit();

            num_joints = articulationChain.Length;

            // Rendering stuff

            if (OVRManager.isHmdPresent & useVR)
            {
                print("VR Active");
            }
            else
            {
                // Make it so the VR rig just acts like any old camera
                Vector3 temp = new Vector3(-0.3f, -0.4f, -0.1f);
                cameraTransform.transform.position = temp;
                Vector3 rot = new Vector3(20f, 30f, 0f);
                cameraTransform.transform.rotation = Quaternion.Euler(rot);
            }

            shoulderRenderTexture = new RenderTexture(256, 256, 24, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_SRGB); // this is very important
            shoulderRenderTexture.Create();
            gripperRenderTexture = new RenderTexture(64, 64, 24, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_SRGB);    // this is very important
            gripperRenderTexture.Create();

            reset_to_default();
        }
 private void GetDevices()
 {
     InputDevices.GetDevicesWithCharacteristics(InputDeviceCharacteristics.Controller, _devices);
     _lastButtonValue = new bool[_devices.Count];
 }
Пример #3
0
        public virtual void UpdateInputs()
        {
            string name = transform.name;

            // SteamVR uses an action system
            if (InputSource == XRInputSource.SteamVR && SteamVRSupport)
            {
                UpdateSteamInput();
            }
            // Use OVRInput to get more Oculus Specific inputs, such as "Near Touch"
            else if (InputSource == XRInputSource.OVRInput || !XRInputSupported)
            {
                LeftThumbstickAxis  = ApplyDeadZones(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick), ThumbstickDeadzoneX, ThumbstickDeadzoneY);
                RightThumbstickAxis = ApplyDeadZones(OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick), ThumbstickDeadzoneX, ThumbstickDeadzoneY);

                LeftGrip     = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.LTouch);
                LeftGripDown = OVRInput.GetDown(OVRInput.Button.PrimaryHandTrigger, OVRInput.Controller.LTouch);

                RightGrip     = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.RTouch);
                RightGripDown = OVRInput.GetDown(OVRInput.Button.PrimaryHandTrigger, OVRInput.Controller.RTouch);

                LeftTrigger     = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.LTouch);
                LeftTriggerDown = OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger, OVRInput.Controller.LTouch);

                RightTrigger     = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.RTouch);
                RightTriggerDown = OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger, OVRInput.Controller.RTouch);

                LeftTriggerNear = OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, OVRInput.Controller.LTouch);
                LeftThumbNear   = OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, OVRInput.Controller.LTouch);

                RightTriggerNear = OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, OVRInput.Controller.RTouch);
                RightThumbNear   = OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, OVRInput.Controller.RTouch);

                SetOVRButtons();
            }
            else
            {
#if UNITY_2019_3_OR_NEWER
                // Refresh XR devices
                InputDevices.GetDevices(devices);

                // Left XR Controller
                var leftHandedControllers = new List <InputDevice>();
                var dc = InputDeviceCharacteristics.HeldInHand | InputDeviceCharacteristics.Left | InputDeviceCharacteristics.Controller;
                InputDevices.GetDevicesWithCharacteristics(dc, leftHandedControllers);
                var primaryLeftController = leftHandedControllers.FirstOrDefault();

                // Right XR Controller
                var rightHandedControllers = new List <InputDevice>();
                dc = InputDeviceCharacteristics.HeldInHand | InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller;
                InputDevices.GetDevicesWithCharacteristics(dc, rightHandedControllers);
                var primaryRightController = rightHandedControllers.FirstOrDefault();

                LeftThumbstickAxis  = ApplyDeadZones(getFeatureUsage(primaryLeftController, CommonUsages.primary2DAxis), ThumbstickDeadzoneX, ThumbstickDeadzoneY);
                RightThumbstickAxis = ApplyDeadZones(getFeatureUsage(primaryRightController, CommonUsages.primary2DAxis), ThumbstickDeadzoneX, ThumbstickDeadzoneY);

                // Store copy of previous value so we can determin if we need to call OnDownEvent
                var prevVal = LeftGrip;
                LeftGrip     = getFeatureUsage(primaryLeftController, CommonUsages.grip);
                LeftGripDown = prevVal < _downThreshold && LeftGrip >= _downThreshold;

                prevVal       = RightGrip;
                RightGrip     = getFeatureUsage(primaryRightController, CommonUsages.grip);
                RightGripDown = prevVal < _downThreshold && RightGrip >= _downThreshold;

                prevVal         = LeftTrigger;
                LeftTrigger     = getFeatureUsage(primaryLeftController, CommonUsages.trigger);
                LeftTriggerDown = prevVal < _downThreshold && LeftTrigger >= _downThreshold;

                prevVal          = RightTrigger;
                RightTrigger     = getFeatureUsage(primaryRightController, CommonUsages.trigger);
                RightTriggerDown = prevVal < _downThreshold && RightTrigger >= _downThreshold;

                LeftTriggerNear = getFeatureUsage(primaryLeftController, CommonUsages.indexTouch) > 0;
                LeftThumbNear   = getFeatureUsage(primaryLeftController, CommonUsages.thumbTouch) > 0;

                RightTriggerNear = getFeatureUsage(primaryRightController, CommonUsages.indexTouch) > 0;
                RightThumbNear   = getFeatureUsage(primaryRightController, CommonUsages.thumbTouch) > 0;

                // Let OVRInput Handle the remaining buttons
                SetOVRButtons();
#endif
            }
        }
    private void Update()
    {
        InputDevices.GetDevicesWithCharacteristics(InputDeviceCharacteristics.Controller, controllers);

        CheckPause(controllers);
    }
Пример #5
0
    private void Climb()
    {
        InputDevices.GetDeviceAtXRNode(climbingHand.controllerNode).TryGetFeatureValue(CommonUsages.deviceVelocity, out Vector3 velocity);

        character.Move(transform.rotation * -velocity * Time.fixedDeltaTime);
    }
 private void Start()
 {
     rightHand = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);
 }
Пример #7
0
    void Update()
    {
        InputDevice device = InputDevices.GetDeviceAtXRNode(inputSource);

        device.TryGetFeatureValue(CommonUsages.primary2DAxis, out inputAxis);

        prevAmount = moveAmount;
        //Get the input
        //float inputX = Input.GetAxisRaw("Horizontal");
        //float inputZ = Input.GetAxisRaw("Vertical");



        //Get movement direction
        Vector3 forwardDir = Camera.main.transform.forward.normalized;

        forwardDir = forwardDir * inputAxis.y;                                            // + Camera.main.transform.right.normalized * inputX;
        Vector3 leftDir = Vector3.Cross(Camera.main.transform.up, forwardDir).normalized; //left axis is cross product of camera direction and forward

        leftDir = leftDir * inputAxis.x;

        if (isGrounded && (forwardDir != Vector3.zero || leftDir != Vector3.zero))
        {
            prevMov = forwardDir + leftDir;
        }

        /*if (TriggerInteraction.detached_flag == true && TriggerInteraction.moving == false)
         * {
         *      //Navigation code here
         *      isGrounded = true;
         *
         *      moveAmount = forwardDir * detach_walkSpeed;
         * }*/
        else if (TriggerInteraction.detached_flag == false)
        {
        }

        Vector3 targetMoveAmount;

        if (inputAxis.y > 0)
        {
            targetMoveAmount = (forwardDir + leftDir) * walkSpeed;
        }
        else
        {
            targetMoveAmount = (forwardDir - leftDir) * walkSpeed;
        }
        if (isGrounded)                                                                                                     //player keeps moving in mid-air based on previous input rather than current input
        {
            moveAmount = Vector3.SmoothDamp(moveAmount, targetMoveAmount, ref smoothMoveVelocity, .1f);
        }
        else
        {
            moveAmount = prevAmount;
        }

        if (moveAmount.magnitude < .3f)
        {
            isMoving = false;
        }
        else
        {
            isMoving = true;
        }


        //if(Input.GetButtonDown("Fire1"))                                                            //map this to contrller later
        //{
        //    Gravity2 nearestNode = FindNearestNode();
        //    if (isWalkOn)
        //    {
        //        isWalkOn = false;
        //        nearestNode.isInGravityPull = true;
        //    }
        //    else
        //    {
        //        isWalkOn = true;
        //        nearestNode.isInGravityPull = false;
        //    }

        //}



        //jump nmechanics

        /*if (Input.GetButtonDown("Jump"))                                                    //map this to controller later
         * {
         *      if (isGrounded)
         *      {
         *              isJumping = true;
         *              playerRigidBody.AddForce(transform.up * jumpForce);
         *              //I can stop what ever music is playing when the user jumps
         *              if (localSound.isPlaying)
         *                      localSound.Stop();
         *      }
         * }*/

        //grounded check
        Ray        ray = new Ray(transform.position, -transform.up);                    //may need to change this in my setup to child capsule
        RaycastHit hit;

        if (!rayDelay && Physics.Raycast(ray, out hit, 1 + .1f, groundedMask))
        {
            //print("grounded");
            isJumping  = false;
            isGrounded = true;
        }
        else
        {
            isGrounded = false;
        }
        // the following is used for the looping sound when your on a planet.
        if (previousPlanet == null && GravMgr.currentPlanet != null)
        {                   //instantiate the previous planet variable
            previousPlanet = GravMgr.currentPlanet;
            PlayWalkingLoop();
        }
        else if (!GameObject.Equals(previousPlanet, GravMgr.currentPlanet))
        {         //check if a new planet has been selected
            PlayWalkingLoop();
            previousPlanet = GravMgr.currentPlanet;
        }
    }
Пример #8
0
 void Update()
 {
     InputDevices.GetDeviceAtXRNode(handInputDevice).TryGetFeatureValue(UnityEngine.XR.CommonUsages.deviceVelocity, out deviceVelocity);
 }
Пример #9
0
 // Start is called before the first frame update
 void Start()
 {
     device = InputDevices.GetDeviceAtXRNode(XRNode.RightHand); //오른쪽 조이스틱은 회전(왼쪽은 이동)
 }
Пример #10
0
 private void Start()
 {
     _head = InputDevices.GetDeviceAtXRNode(XRNode.Head);
     Recenter();
 }
Пример #11
0
        private void Update()
        {
            var node   = _hand == Hand.Left ? XRNode.LeftHand : XRNode.RightHand;
            var device = InputDevices.GetDeviceAtXRNode(node);

            // Match this transform to the controller's position & rotation
            InputTracking.GetNodeStates(_states);
            IsConnected = false;
            for (var i = 0; i < _states.Count; i++)
            {
                var state = _states[i];
                if (state.nodeType == node)
                {
                    if (state.TryGetPosition(out var pos))
                    {
                        _xform.localPosition = pos;
                        if (state.TryGetRotation(out var rot))
                        {
                            _xform.localRotation = rot;
                            IsConnected          = true;
                        }
                    }
                    break;
                }
            }

            // Update the states of the Grip and Trigger analog buttons
            if (device.TryGetFeatureValue(CommonUsages.grip, out var value))
            {
                Grip.Update(value);
            }

            if (device.TryGetFeatureValue(CommonUsages.trigger, out value))
            {
                Trigger.Update(value);
            }


            // Update the A/X button, interpreting a touch with a value that can be seen in the ButtonState's analog value
            if (device.TryGetFeatureValue(CommonUsages.primaryButton, out var buttonValue))
            {
                if (buttonValue)
                {
                    AorX.Update(1f);
                }
                else if (device.TryGetFeatureValue(CommonUsages.primaryTouch, out buttonValue))
                {
                    AorX.Update(buttonValue ? 0.25f : 0f);
                }
                else
                {
                    AorX.Update(0f);
                }
            }

            // Update the B/Y button, interpreting a touch with a value that can be seen in the ButtonState's analog value
            if (device.TryGetFeatureValue(CommonUsages.secondaryButton, out buttonValue))
            {
                if (buttonValue)
                {
                    BorY.Update(1f);
                }
                else if (device.TryGetFeatureValue(CommonUsages.secondaryTouch, out buttonValue))
                {
                    BorY.Update(buttonValue ? 0.25f : 0f);
                }
                else
                {
                    BorY.Update(0f);
                }
            }
        }
Пример #12
0
 protected override InputDevice CheckDevice()
 {
     return(InputDevices.GetDeviceAtXRNode(XRNode.Head));
 }
Пример #13
0
    /*
     * Handle toggling of targetting as well as switching between targets. While holding down
     * target button, player can cycle through targets.
     */
    void TryTargetting()
    {
        float       deadStickThreshold = 0.5f;
        InputDevice xbox = InputDevices.GetAllInputDevices() [(int)InputDevices.ControllerTypes.XBox];
        float       rightStickPressedAxis = Input.GetAxisRaw(RBInput.ConcatPlayerIndex(InputStrings.TARGET, PlayerIndex, xbox));
        bool        rightStickPressed     = rightStickPressedAxis >= 0.99 && rightStickAvailable;
        // Consolidate bool for PC and XBox
        bool isTargetPressed = RBInput.GetButtonDownForPlayer(InputStrings.TARGET, PlayerIndex) ||
                               rightStickPressed;

        // Toggle Targeting on and off
        if (isTargetPressed)
        {
            rightStickAvailable = false;
            if (!fighter.isLockedOn)
            {
                TargetNearest();
            }
            else
            {
                fighter.LoseTarget();
            }
        }

        // Switch between targets
        if (fighter.isLockedOn)
        {
            // PC and Controller controls likely should diverge here due to right stick use
            InputDevice pc = InputDevices.GetAllInputDevices() [(int)InputDevices.ControllerTypes.Keyboard];
            float       horizontalTargetAxis = Input.GetAxisRaw(RBInput.ConcatPlayerIndex(InputStrings.TARGETHORIZONTAL, PlayerIndex, xbox));
            float       verticalTargetAxis   = -Input.GetAxisRaw(RBInput.ConcatPlayerIndex(InputStrings.TARGETVERTCIAL, PlayerIndex, xbox));

            // Move target in axis direction
            bool  changingTarget = false;
            float horizontal     = 0;
            float vertical       = 0;

            //
            // Read in PC input
            //
            // Set Horizontal Input for PC
            if (Input.GetButtonDown(RBInput.ConcatPlayerIndex(InputStrings.TARGETLEFT, PlayerIndex, pc)))
            {
                //|| )) {
                //rightStickHorizontalAvailable = false;
                //TargetNext (true);
                horizontal     = -1;
                changingTarget = true;
            }
            else if (Input.GetButtonDown(RBInput.ConcatPlayerIndex(InputStrings.TARGETRIGHT, PlayerIndex, pc)))
            {
                horizontal     = 1;
                changingTarget = true;
            }
            // Set Vertical Input
            if (Input.GetButtonDown(RBInput.ConcatPlayerIndex(InputStrings.TARGETDOWN, PlayerIndex, pc)))
            {
                vertical       = -1;
                changingTarget = true;
            }
            else if (Input.GetButtonDown(RBInput.ConcatPlayerIndex(InputStrings.TARGETUP, PlayerIndex, pc)))
            {
                vertical       = 1;
                changingTarget = true;
            }

            //
            // Read in XBox input
            //
            // Set Horizontal and Vertical values for XBox
            bool horizontalAxisPressed = rightStickAxisAvailable &&
                                         (horizontalTargetAxis <-deadStickThreshold || horizontalTargetAxis> deadStickThreshold);
            bool verticalAxisPressed = rightStickAxisAvailable &&
                                       (verticalTargetAxis <-deadStickThreshold || verticalTargetAxis> deadStickThreshold);
            if (horizontalAxisPressed || verticalAxisPressed)
            {
                rightStickAxisAvailable = false;
                TargetNearDirection(horizontalTargetAxis, verticalTargetAxis);
                changingTarget = true;
            }

            // Make target change
            if (changingTarget)
            {
                TargetNearDirection(horizontal, vertical);
            }

            // Enforce stick behavior like a button
            rightStickAxisAvailable = IsAxisDead(horizontalTargetAxis, deadStickThreshold) &&
                                      IsAxisDead(verticalTargetAxis, deadStickThreshold);
        }
        rightStickAvailable = IsAxisDead(rightStickPressedAxis, deadStickThreshold);
    }
        // ReSharper restore UnusedMember.Local
        #pragma warning restore IDE0051
        #endregion

        private void UpdateInputDevices()
        {
            var inputDevices                = new List <InputDevice>();
            var unassignedDevices           = new Queue <InputDevice>();
            var openVRDevicesBySerialNumber = new Dictionary <string, uint>();

            InputDevices.GetDevices(inputDevices);

            var deviceRoles = new Dictionary <string, TrackedDeviceRole>(inputDevices.Count);

            if (_isOpenVRRunning)
            {
                string[] serialNumbers = OpenVRWrapper.GetTrackedDeviceSerialNumbers();

                for (uint i = 0; i < serialNumbers.Length; i++)
                {
                    if (string.IsNullOrEmpty(serialNumbers[i]))
                    {
                        continue;
                    }

                    Plugin.logger.Debug($"Got serial number \"{serialNumbers[i]}\" for device at index {i}");
                    openVRDevicesBySerialNumber.Add(serialNumbers[i], i);
                }
            }

            InputDevice?headInputDevice      = null;
            InputDevice?leftHandInputDevice  = null;
            InputDevice?rightHandInputDevice = null;
            InputDevice?waistInputDevice     = null;
            InputDevice?leftFootInputDevice  = null;
            InputDevice?rightFootInputDevice = null;

            int trackerCount = 0;

            foreach (InputDevice device in inputDevices)
            {
                if (!device.isValid)
                {
                    continue;
                }

                deviceRoles.Add(device.name, TrackedDeviceRole.Unknown);

                if (!_foundDevices.Contains(device.name))
                {
                    Plugin.logger.Info($"Found new input device \"{device.name}\" with serial number \"{device.serialNumber}\"");
                    _foundDevices.Add(device.name);
                }

                if (device.HasCharacteristics(InputDeviceCharacteristics.HeadMounted))
                {
                    headInputDevice = device;
                }
                else if (device.HasCharacteristics(InputDeviceCharacteristics.HeldInHand |
                                                   InputDeviceCharacteristics.Left))
                {
                    leftHandInputDevice = device;
                }
                else if (device.HasCharacteristics(InputDeviceCharacteristics.HeldInHand |
                                                   InputDeviceCharacteristics.Right))
                {
                    rightHandInputDevice = device;
                }
                else if (device.HasCharacteristics(InputDeviceCharacteristics.TrackedDevice) && !device.HasCharacteristics(InputDeviceCharacteristics.TrackingReference))
                {
                    if (_isOpenVRRunning &&
                        !string.IsNullOrEmpty(device.serialNumber) &&
                        openVRDevicesBySerialNumber.TryGetValue(device.serialNumber, out uint openVRDeviceId))
                    {
                        // try to figure out tracker role using OpenVR
                        var role = OpenVRWrapper.GetTrackedDeviceRole(openVRDeviceId);
                        deviceRoles[device.name] = role;

                        Plugin.logger.Info($"Tracker \"{device.name}\" has role {role}");

                        switch (role)
                        {
                        case TrackedDeviceRole.Waist:
                            waistInputDevice = device;
                            break;

                        case TrackedDeviceRole.LeftFoot:
                            leftFootInputDevice = device;
                            break;

                        case TrackedDeviceRole.RightFoot:
                            rightFootInputDevice = device;
                            break;

                        default:
                            unassignedDevices.Enqueue(device);
                            break;
                        }
                    }
                    else
                    {
                        unassignedDevices.Enqueue(device);
                    }

                    trackerCount++;
                }
            }

            // fallback if OpenVR tracker roles aren't set/supported
            if (leftFootInputDevice == null && trackerCount >= 2 && unassignedDevices.Count > 0)
            {
                leftFootInputDevice = unassignedDevices.Dequeue();
            }

            if (rightFootInputDevice == null && trackerCount >= 2 && unassignedDevices.Count > 0)
            {
                rightFootInputDevice = unassignedDevices.Dequeue();
            }

            if (waistInputDevice == null && unassignedDevices.Count > 0)
            {
                waistInputDevice = unassignedDevices.Dequeue();
            }

            AssignTrackedDevice(head, headInputDevice, DeviceUse.Head, headInputDevice.HasValue      ? deviceRoles[headInputDevice.Value.name]      : TrackedDeviceRole.Unknown);
            AssignTrackedDevice(leftHand, leftHandInputDevice, DeviceUse.LeftHand, leftHandInputDevice.HasValue  ? deviceRoles[leftHandInputDevice.Value.name]  : TrackedDeviceRole.Unknown);
            AssignTrackedDevice(rightHand, rightHandInputDevice, DeviceUse.RightHand, rightHandInputDevice.HasValue ? deviceRoles[rightHandInputDevice.Value.name] : TrackedDeviceRole.Unknown);
            AssignTrackedDevice(waist, waistInputDevice, DeviceUse.Waist, waistInputDevice.HasValue     ? deviceRoles[waistInputDevice.Value.name]     : TrackedDeviceRole.Unknown);
            AssignTrackedDevice(leftFoot, leftFootInputDevice, DeviceUse.LeftFoot, leftFootInputDevice.HasValue  ? deviceRoles[leftFootInputDevice.Value.name]  : TrackedDeviceRole.Unknown);
            AssignTrackedDevice(rightFoot, rightFootInputDevice, DeviceUse.RightFoot, rightFootInputDevice.HasValue ? deviceRoles[rightFootInputDevice.Value.name] : TrackedDeviceRole.Unknown);

            foreach (string deviceName in _foundDevices.ToList())
            {
                if (!inputDevices.Exists(d => d.name == deviceName))
                {
                    Plugin.logger.Info($"Lost device \"{deviceName}\"");
                    _foundDevices.Remove(deviceName);
                }
            }
        }
Пример #15
0
    void Update()
    {
        if (Input.GetKey("escape"))
        {
            Application.Quit();
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            ExportOBJ();
        }

        if (Input.GetKeyDown(KeyCode.Backspace))
        {
            Undo();
        }

        lastTriggering      = triggering;
        lastUndo            = undo;
        lastTriggeringRight = triggeringRight;
        lastUndoRight       = undoRight;

        List <XRNodeState> xrNodes = new List <XRNodeState> ();

        InputTracking.GetNodeStates(xrNodes);

        for (int i = 0; i < xrNodes.Count; i++)
        {
            // lefthand
            if (xrNodes[i].nodeType == XRNode.LeftHand)
            {
                Vector3 newHandPosition;
                xrNodes[i].TryGetPosition(out newHandPosition);
                leftHand.transform.localPosition = newHandPosition;

                Quaternion newHandRotation;
                xrNodes[i].TryGetRotation(out newHandRotation);
                leftHand.transform.localRotation = newHandRotation;

                InputDevices.GetDeviceAtXRNode(xrNodes[i].nodeType).TryGetFeatureValue(CommonUsages.trigger, out triggerPress);
                InputDevices.GetDeviceAtXRNode(xrNodes[i].nodeType).TryGetFeatureValue(CommonUsages.grip, out grabPress);

                if (triggerPress > 0.6f)
                {
                    triggering = true;
                }
                else
                {
                    triggering = false;
                }

                if (grabPress > 0.6f)
                {
                    undo = true;
                }
                else
                {
                    undo = false;
                }
            }

            // righthand
            if (xrNodes[i].nodeType == XRNode.RightHand)
            {
                Vector3 newHandPosition;
                xrNodes[i].TryGetPosition(out newHandPosition);
                rightHand.transform.localPosition = newHandPosition;

                Quaternion newHandRotation;
                xrNodes[i].TryGetRotation(out newHandRotation);
                rightHand.transform.localRotation = newHandRotation;

                InputDevices.GetDeviceAtXRNode(xrNodes[i].nodeType).TryGetFeatureValue(CommonUsages.trigger, out triggerPressRight);
                InputDevices.GetDeviceAtXRNode(xrNodes[i].nodeType).TryGetFeatureValue(CommonUsages.grip, out grabPressRight);

                if (triggerPressRight > 0.6f)
                {
                    triggeringRight = true;
                }
                else
                {
                    triggeringRight = false;
                }

                if (grabPressRight > 0.6f)
                {
                    undoRight = true;
                }
                else
                {
                    undoRight = false;
                }
            }

            //  }
            else
            {
            }
        }

        if (triggering == true && lastTriggering == false)
        {
            StartCreatingStrand(leftHand);
        }
        if (lastTriggering == true && triggering == false)
        {
            StopCreatingStrand();
        }

        if (undo == true && lastUndo == false)
        {
            Undo();
        }
        if (lastUndo == true && undo == false)
        {
        }

        // right
        if (triggeringRight == true && lastTriggeringRight == false)
        {
            StartCreatingStrand(rightHand);
        }
        if (lastTriggeringRight == true && triggeringRight == false)
        {
            StopCreatingStrand();
        }

        if (undoRight == true && lastUndoRight == false)
        {
            Undo();
        }
        if (lastUndoRight == true && undoRight == false)
        {
        }
    }
Пример #16
0
        void Update()
        {
            // Use Unity XR Input when enabled. When using WebXR, updates are performed onControllerUpdate.
            List <InputDevice> devices = new List <InputDevice>();

            InputDevices.GetDevicesWithCharacteristics(InputDeviceCharacteristics.HeadMounted, devices);
            bool XRisPresent = devices.Count > 0;

            if (!XRisPresent)
            {
                return;
            }

            if (!xr_inited)
            {
                InitXR();
            }

            SetVisible(true);

            List <XRNodeState> mNodeStates = new List <XRNodeState>();
            Vector3            mHeadPos    = Vector3.zero;
            Quaternion         mHeadRot    = Quaternion.identity;
            Vector3            mHandPos    = Vector3.zero;
            Quaternion         mHandRot    = Quaternion.identity;

            if (this.hand == WebXRControllerHand.LEFT)
            {
                handNode = XRNode.LeftHand;
            }

            if (this.hand == WebXRControllerHand.RIGHT)
            {
                handNode = XRNode.RightHand;
            }

            InputTracking.GetNodeStates(mNodeStates);

            foreach (XRNodeState nodeState in mNodeStates)
            {
                switch (nodeState.nodeType)
                {
                case XRNode.Head:
                    nodeState.TryGetPosition(out mHeadPos);
                    nodeState.TryGetRotation(out mHeadRot);
                    break;

                case XRNode.LeftHand:
                    if (this.hand == WebXRControllerHand.LEFT)
                    {
                        nodeState.TryGetPosition(out mHandPos);
                        nodeState.TryGetRotation(out mHandRot);
                    }
                    break;

                case XRNode.RightHand:
                    if (this.hand == WebXRControllerHand.RIGHT)
                    {
                        nodeState.TryGetPosition(out mHandPos);
                        nodeState.TryGetRotation(out mHandRot);
                    }
                    break;
                }
            }


            if (this.simulate3dof)
            {
                _t.localPosition = applyArmModel(
                    mHeadPos, // we use head position as origin
                    mHandRot,
                    mHeadRot);
                _t.localRotation = mHandRot;
            }
            else
            {
                _t.localPosition = mHandPos;
                _t.localRotation = mHandRot;
            }

            foreach (WebXRControllerInput input in inputMap.inputs)
            {
                if (!input.unityInputIsButton)
                {
                    if (Input.GetAxis(input.unityInputName) != 0)
                    {
                        SetButtonState(input.actionName, true, Input.GetAxis(input.unityInputName));
                    }
                    if (Input.GetAxis(input.unityInputName) < 1)
                    {
                        SetButtonState(input.actionName, false, Input.GetAxis(input.unityInputName));
                    }
                }
            }
        }
Пример #17
0
        private void Update()
        {
            bool        controllerValid  = false;
            InputDevice controllerDevice = InputDevices.GetDeviceAtXRNode(s_controllerNode);

#if USING_STEAMVR
            controllerValid = true;
#else
            controllerValid = controllerDevice.isValid;
#endif
            // Debug.Log("Input device: " + controllerDevice.ToString());
            if (controllerValid)
            {
                //Trigger
                float triggerValue = 0.0f;
                bool  featureGrabbed;
#if USING_STEAMVR
                triggerValue   = s_triggerState.GetAxis(_hand);
                featureGrabbed = true;
#else
                featureGrabbed = controllerDevice.TryGetFeatureValue(CommonUsages.trigger, out triggerValue);
#endif
                if (featureGrabbed)
                {
                    // Debug.Log("Trigger value: " + triggerValue);
                    if (triggerValue > 0.3f && _previousTriggerValue < 0.3f)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Press, (InputFeatureUsage)CommonUsages.trigger, s_controllerNode, triggerValue);
                        Debug.Log("Trigger pressed: " + s_controllerNode.ToString());
                    }
                    if (triggerValue < 0.001f && _previousTriggerValue > 0.001f)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Release, (InputFeatureUsage)CommonUsages.trigger, s_controllerNode, triggerValue);
                    }
                    _previousTriggerValue = triggerValue;
                }
                else
                {
                    Debug.Log("Getting trigger info failed!");
                }
                //Grip
                float gripValue = 0.0f;
#if USING_STEAMVR
                gripValue = s_gripState.GetAxis(_hand);
#else
                featureGrabbed = controllerDevice.TryGetFeatureValue(CommonUsages.grip, out gripValue);
#endif
                if (featureGrabbed)
                {
                    if (gripValue > 0.01f && _previousGripValue < 0.01f)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Press, (InputFeatureUsage)CommonUsages.grip, s_controllerNode, gripValue);
                        Debug.Log("Grip pressed: " + s_controllerNode.ToString());
                    }
                    if (gripValue < 0.01f && _previousGripValue > 0.01f)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Release, (InputFeatureUsage)CommonUsages.grip, s_controllerNode, gripValue);
                    }
                    _previousGripValue = gripValue;
                }
                else
                {
                    Debug.Log("Getting grip info failed!");
                }
#if USING_STEAMVR
#else
                //MenuButon, ONLY left
                bool menuButtonValue = false;
                featureGrabbed = false;
                if (controllerDevice.TryGetFeatureValue(CommonUsages.menuButton, out menuButtonValue) && s_controllerNode == XRNode.LeftHand)
                {
                    if (menuButtonValue && !_previousMenuButtonValue)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Press, (InputFeatureUsage)CommonUsages.menuButton, s_controllerNode, 1.0f);
                    }
                    if (menuButtonValue && !_previousMenuButtonValue)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Release, (InputFeatureUsage)CommonUsages.menuButton, s_controllerNode, 0.0f);
                    }
                    _previousMenuButtonValue = menuButtonValue;
                }
#endif
                //Primary Button
                bool primaryButtonValue = false;
                if (controllerDevice.TryGetFeatureValue(CommonUsages.primaryButton, out primaryButtonValue))
                {
                    if (primaryButtonValue && !_previousPrimaryButton)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Press, (InputFeatureUsage)CommonUsages.primaryButton, s_controllerNode, 1.0f);
                        Debug.Log("Primary button Pressed");
                    }
                    if (primaryButtonValue && !_previousPrimaryButton)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Release, (InputFeatureUsage)CommonUsages.primaryButton, s_controllerNode, 0.0f);
                    }
                    _previousPrimaryButton = primaryButtonValue;
                }
                //Secondary Button
                bool secondaryButtonValue = false;
                if (controllerDevice.TryGetFeatureValue(CommonUsages.secondaryButton, out secondaryButtonValue))
                {
                    if (secondaryButtonValue && !_previousSecondaryButton)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Press, (InputFeatureUsage)CommonUsages.secondaryButton, s_controllerNode, 1.0f);
                        Debug.Log("Secondary button Pressed");
                    }
                    if (secondaryButtonValue && !_previousSecondaryButton)
                    {
                        JAVR_ControllerInputEvents.InputDeviceButtonAction(JAVR_ControllerInputAction.Release, (InputFeatureUsage)CommonUsages.secondaryButton, s_controllerNode, 0.0f);
                    }
                    _previousSecondaryButton = secondaryButtonValue;
                }
            }
        }
Пример #18
0
    // Update is called once per frame
    void Update()
    {
        leftController  = InputDevices.GetDeviceAtXRNode(leftHand);
        rightController = InputDevices.GetDeviceAtXRNode(rightHand);

        leftAnim.SetFloat("Trigger", leftTrigger);
        leftAnim.SetFloat("Grip", leftGrip);
        leftAnim.SetFloat("Joy X", leftStick.x);
        leftAnim.SetFloat("Joy Y", leftStick.y);
        if (leftPrimary)
        {
            leftAnim.SetFloat("Button 1", 1);
        }
        else
        {
            leftAnim.SetFloat("Button 1", 0);
        }

        if (leftSecondary)
        {
            leftAnim.SetFloat("Button 2", 1);
        }
        else
        {
            leftAnim.SetFloat("Button 2", 0);
        }

        rightAnim.SetFloat("Trigger", rightTrigger);
        rightAnim.SetFloat("Grip", rightGrip);
        rightAnim.SetFloat("Joy X", rightStick.x);
        rightAnim.SetFloat("Joy Y", rightStick.y);
        if (rightPrimary)
        {
            rightAnim.SetFloat("Button 1", 1);
        }
        else
        {
            rightAnim.SetFloat("Button 1", 0);
        }

        if (rightSecondary)
        {
            rightAnim.SetFloat("Button 2", 1);
        }
        else
        {
            rightAnim.SetFloat("Button 2", 0);
        }



        leftController.TryGetFeatureValue(CommonUsages.primary2DAxis, out leftStick);
        leftController.TryGetFeatureValue(CommonUsages.trigger, out leftTrigger);
        leftController.TryGetFeatureValue(CommonUsages.grip, out leftGrip);
        leftController.TryGetFeatureValue(CommonUsages.primaryButton, out leftPrimary);
        leftController.TryGetFeatureValue(CommonUsages.secondaryButton, out leftSecondary);

        rightController.TryGetFeatureValue(CommonUsages.primary2DAxis, out rightStick);
        rightController.TryGetFeatureValue(CommonUsages.trigger, out rightTrigger);
        rightController.TryGetFeatureValue(CommonUsages.grip, out rightGrip);
        rightController.TryGetFeatureValue(CommonUsages.primaryButton, out rightPrimary);
        rightController.TryGetFeatureValue(CommonUsages.secondaryButton, out rightSecondary);
    }
Пример #19
0
        void ChooseVRControllerModels()
        {
            var type = VRControllerType.Generic;

            var deviceName = InputDevices.GetDeviceAtXRNode(XRNode.LeftHand).name;

            Debug.Log($"Device name : {deviceName}");
            if (!string.IsNullOrEmpty(deviceName))
            {
                deviceName = Regex.Replace(deviceName.ToLower(), @"\s+", "");
                if (deviceName.Contains("quest2"))
                {
                    //TODO: Not supported yet
                    type = VRControllerType.Generic;
                    //type = VRControllerType.OculusTouchQuest2;
                }
                else if (deviceName.Contains("rifts") ||
                         deviceName.Contains("touchs") ||
                         deviceName.Contains("quest"))
                {
                    //TODO: Not supported yet
                    type = VRControllerType.Generic;
                    //type = VRControllerType.OculusTouchS;
                }
                else if (deviceName.Contains("oculus") ||
                         deviceName.Contains("rift") ||
                         deviceName.Contains("touch"))
                {
                    type = VRControllerType.OculusTouch;
                }
                else if (deviceName.Contains("index") ||
                         deviceName.Contains("knuckle"))
                {
                    //TODO: Not supported yet
                    type = VRControllerType.ViveIndex;
                }
                else if (deviceName.Contains("cosmos"))
                {
                    //TODO: Not supported yet
                    type = VRControllerType.ViveCosmos;
                }
                else if (deviceName.Contains("vive") ||
                         deviceName.Contains("valve"))
                {
                    type = VRControllerType.ViveWand;
                }
                else
                {
                    type = VRControllerType.Generic;
                }
            }

            Debug.Log(type);

            var vrController = m_VRControllers.FirstOrDefault(c => c.Type == type);

            if (vrController != null)
            {
                Instantiate(vrController.LeftPrefab, m_LeftHandController.transform);
                Instantiate(vrController.RightPrefab, m_RightHandController.transform);
            }
        }
 private void GetDevice()
 {
     InputDevices.GetDevicesAtXRNode(controllerNode, devices);
     controller = devices.FirstOrDefault();
 }
Пример #21
0
 // Get XR controllers associated with the nodes
 void GetDevice()
 {
     InputDevices.GetDevicesAtXRNode(leftControllerNode, leftNodeDevices);
     InputDevices.GetDevicesAtXRNode(rightControllerNode, rightNodeDevices);
 }
Пример #22
0
        private void FixedUpdate()
        {
            var leftHand  = InputDevices.GetDeviceAtXRNode(XRNode.LeftHand);
            var rightHand = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);

            leftHand.TryGetFeatureValue(CommonUsages.primary2DAxis, out var leftStick);
            rightHand.TryGetFeatureValue(CommonUsages.primary2DAxis, out var rightStick);

            var absL  = Mathf.Abs(leftStick.y);
            var absR  = Mathf.Abs(rightStick.y);
            var sign  = Mathf.Sign(leftStick.y + rightStick.y);
            var speed = Mathf.Abs(leftStick.y + rightStick.y);

            speed    *= speed * speed;
            speed     = speed > 1f ? Mathf.Lerp(_walkSpeed, _runSpeed, speed - 1f) : Mathf.Lerp(0f, _walkSpeed, speed);
            _velocity = Mathf.Lerp(_velocity, speed * sign, _smoothT);

            // If either hand is beyond a specified radius from the head (on the XZ-plane) that hand's direction is used, otherwise the head's direction is used.
            var leftDeltaXZ = (_leftHand.Position - _head.position);

            leftDeltaXZ.y = 0f;
            var rightDeltaXZ = (_rightHand.Position - _head.position);

            rightDeltaXZ.y = 0f;
            var leftPointing  = leftDeltaXZ.sqrMagnitude > (_gazeRadius * _gazeRadius) && absL > 0.25f;
            var rightPointing = rightDeltaXZ.sqrMagnitude > (_gazeRadius * _gazeRadius) && absR > 0.25f;

            // Change between gaze and controller direction?
            //if (absL < 0.1f && absR < 0.1f)
            {
                _usingGaze = !leftPointing && !rightPointing;
            }

            if (_usingGaze)
            {
                // Gaze controls direction
                var headAngle = _head.eulerAngles.y * Mathf.Deg2Rad;
                _direction = new Vector3(Mathf.Sin(headAngle), 0f, Mathf.Cos(headAngle));
            }
            else
            {
                // Blend the directions of the two hands, balanced by strength of input
                _direction   = (_left.forward * absL + _right.forward * absR);
                _direction.y = 0f;
                _direction.Normalize();
            }

            _xform.position += _direction * (_velocity * Time.fixedDeltaTime);



            /*
             * bool head = false;
             * if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
             * {
             *      walk = 1f;
             *      head = true;
             * }
             * if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
             * {
             *      walk = 1f;
             *      head = true;
             * }
             *
             * if (Mathf.Abs(walk) < 0.01f)
             * {
             *      _velocity = Mathf.Lerp(_velocity, 0f, 0.125f);
             * }
             * else
             * {
             *      if (head)
             *      {
             *              _direction = _head.forward * (forwardR ? 1f : -1f);
             *      }
             *      else if (right)
             *      {
             *              _direction = _right.forward * (forwardR ? 1f : -1f);
             *      }
             *      else
             *      {
             *              _direction = _left.forward * (forwardL ? 1f : -1f);
             *      }
             *      _direction.y = 0f;
             *      _direction.Normalize();
             *
             *      var speed = 1f - Mathf.Abs(Vector3.Dot(forwardR ? _right.forward : _left.forward, Vector3.down));
             *      _velocity = Mathf.Lerp(_velocity, speed * _walkSpeed, 0.125f);
             * }
             *
             * if (run)
             * {
             *      var speedR = 1f - Mathf.Abs(Vector3.Dot(_right.forward, Vector3.down));
             *      var speedL = 1f - Mathf.Abs(Vector3.Dot(_left.forward, Vector3.down));
             *      var dirR = _right.forward * (forwardR ? 1f : -1f);
             *      var dirL = _left.forward * (forwardL ? 1f : -1f);
             *      _direction = (dirR * speedR) + (dirL * speedL);
             *      _direction.y = 0f;
             *      _direction.Normalize();
             *      _velocity = Mathf.Lerp(_velocity, ((speedR + speedL) * 0.5f) * _runSpeed, 0.125f);
             * }
             *
             * _xform.position += _direction * (_velocity * Time.fixedDeltaTime);
             *
             */
        }
Пример #23
0
 // initialize device and feature references
 private void _Init()
 {
     _device       = InputDevices.GetDeviceAtXRNode(_XRNode);
     _inputFeature = CommonUsages.triggerButton;
 }
Пример #24
0
    // Update is called once per frame
    void Update()
    {
        InputDevice device = InputDevices.GetDeviceAtXRNode(inputSource);

        device.TryGetFeatureValue(CommonUsages.primary2DAxis, out inputAxis);
    }
Пример #25
0
 public InputDeviceMessageHandler(CloseFunction closeFunction, SenderFunction senderFunction, InputDevices inputDevices) : base(closeFunction, senderFunction)
 {
     this.inputDevices = inputDevices;
 }
Пример #26
0
 // Start is called before the first frame update
 void Start()
 {
     device = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);
 }
Пример #27
0
        public virtual void UpdateInputs()
        {
            // SteamVR uses an action system
            if (InputSource == XRInputSource.SteamVR && SteamVRSupport)
            {
                UpdateSteamInput();
            }
            // Use OVRInput to get more Oculus Specific inputs, such as "Near Touch"
            else if (InputSource == XRInputSource.OVRInput)
            {
#if OCULUS_INTEGRATION
                LeftThumbstickAxis  = ApplyDeadZones(OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick), ThumbstickDeadzoneX, ThumbstickDeadzoneY);
                RightThumbstickAxis = ApplyDeadZones(OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick), ThumbstickDeadzoneX, ThumbstickDeadzoneY);

                LeftGrip     = correctValue(OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.LTouch));
                LeftGripDown = OVRInput.GetDown(OVRInput.Button.PrimaryHandTrigger, OVRInput.Controller.LTouch);

                RightGrip     = correctValue(OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.RTouch));
                RightGripDown = OVRInput.GetDown(OVRInput.Button.PrimaryHandTrigger, OVRInput.Controller.RTouch);

                LeftTrigger     = correctValue(OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.LTouch));
                LeftTriggerUp   = OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger, OVRInput.Controller.LTouch);
                LeftTriggerDown = OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger, OVRInput.Controller.LTouch);

                RightTrigger     = correctValue(OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.RTouch));
                RightTriggerUp   = OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger, OVRInput.Controller.RTouch);
                RightTriggerDown = OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger, OVRInput.Controller.RTouch);

                LeftTriggerNear = OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, OVRInput.Controller.LTouch);
                LeftThumbNear   = OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, OVRInput.Controller.LTouch);

                RightTriggerNear = OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, OVRInput.Controller.RTouch);
                RightThumbNear   = OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, OVRInput.Controller.RTouch);

                AButton     = OVRInput.Get(OVRInput.Button.One, OVRInput.Controller.RTouch);
                AButtonDown = OVRInput.GetDown(OVRInput.Button.One, OVRInput.Controller.RTouch);
                AButtonUp   = OVRInput.GetUp(OVRInput.Button.One, OVRInput.Controller.RTouch);

                BButton     = OVRInput.Get(OVRInput.Button.Two);
                BButtonDown = OVRInput.GetDown(OVRInput.Button.Two);
                BButtonUp   = OVRInput.GetUp(OVRInput.Button.Two);

                XButton     = OVRInput.Get(OVRInput.Button.Three);
                XButtonDown = OVRInput.GetDown(OVRInput.Button.Three);
                XButtonUp   = OVRInput.GetUp(OVRInput.Button.Three);

                YButton     = OVRInput.Get(OVRInput.Button.Four);
                YButtonDown = OVRInput.GetDown(OVRInput.Button.Four);
                YButtonUp   = OVRInput.GetUp(OVRInput.Button.Four);

                StartButton     = OVRInput.Get(OVRInput.Button.Start);
                StartButtonDown = OVRInput.GetDown(OVRInput.Button.Start);

                BackButton     = OVRInput.Get(OVRInput.Button.Back);
                BackButtonDown = OVRInput.GetDown(OVRInput.Button.Back);

                LeftThumbstickDown = OVRInput.GetDown(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.LTouch);
                LeftThumbstickUp   = OVRInput.GetUp(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.LTouch);

                RightThumbstickDown = OVRInput.GetDown(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.RTouch);
                RightThumbstickUp   = OVRInput.GetUp(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.RTouch);

                LeftThumbstick  = OVRInput.Get(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.LTouch);
                RightThumbstick = OVRInput.Get(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.RTouch);
#endif
            }
            // Use XRInput
            else
            {
#if UNITY_2019_3_OR_NEWER
                // Refresh XR devices
                InputDevices.GetDevices(devices);

                // Left XR Controller
                var primaryLeftController = GetLeftController();

                // Right XR Controller
                var primaryRightController = GetRightController();

                // For most cases thumbstick is on the primary2DAxis
                // However, if the Controller has both a touchpad and a controller on it (i.e. Valve Index Knuckles) then the thumbstick axis is actually on the secondary axis, not the primary axis
                InputFeatureUsage <Vector2> thumbstickAxis          = SupportsBothTouchPadAndJoystick ? CommonUsages.secondary2DAxis : CommonUsages.primary2DAxis;
                InputFeatureUsage <Vector2> thumbstickAxisSecondary = SupportsBothTouchPadAndJoystick ? CommonUsages.primary2DAxis : CommonUsages.secondary2DAxis;
                InputFeatureUsage <bool>    thumbstickAxisClick     = SupportsBothTouchPadAndJoystick ? CommonUsages.secondary2DAxisClick : CommonUsages.primary2DAxisClick;

                var prevBool = LeftThumbstick;
                LeftThumbstick     = getFeatureUsage(primaryLeftController, thumbstickAxisClick);
                LeftThumbstickDown = prevBool == false && LeftThumbstick == true;
                LeftThumbstickUp   = prevBool == true && LeftThumbstick == false;

                prevBool            = RightThumbstick;
                RightThumbstick     = getFeatureUsage(primaryRightController, thumbstickAxisClick);
                RightThumbstickDown = prevBool == false && RightThumbstick == true;
                RightThumbstickUp   = prevBool == true && RightThumbstick == false;

                LeftTouchPadAxis   = ApplyDeadZones(getFeatureUsage(primaryLeftController, thumbstickAxisSecondary), ThumbstickDeadzoneX, ThumbstickDeadzoneY);
                LeftThumbstickAxis = ApplyDeadZones(getFeatureUsage(primaryLeftController, thumbstickAxis), ThumbstickDeadzoneX, ThumbstickDeadzoneY);

                RightTouchPadAxis   = ApplyDeadZones(getFeatureUsage(primaryRightController, thumbstickAxisSecondary), ThumbstickDeadzoneX, ThumbstickDeadzoneY);
                RightThumbstickAxis = ApplyDeadZones(getFeatureUsage(primaryRightController, thumbstickAxis), ThumbstickDeadzoneX, ThumbstickDeadzoneY);

                // Store copy of previous value so we can determin if we need to call OnDownEvent
                var prevVal = LeftGrip;
                LeftGrip     = correctValue(getFeatureUsage(primaryLeftController, CommonUsages.grip));
                LeftGripDown = prevVal < _downThreshold && LeftGrip >= _downThreshold;

                prevVal       = RightGrip;
                RightGrip     = correctValue(getFeatureUsage(primaryRightController, CommonUsages.grip));
                RightGripDown = prevVal < _downThreshold && RightGrip >= _downThreshold;

                prevVal         = LeftTrigger;
                LeftTrigger     = correctValue(getFeatureUsage(primaryLeftController, CommonUsages.trigger));
                LeftTriggerUp   = LeftTrigger == 0;
                LeftTriggerDown = prevVal < _downThreshold && LeftTrigger >= _downThreshold;

                prevVal          = RightTrigger;
                RightTrigger     = correctValue(getFeatureUsage(primaryRightController, CommonUsages.trigger));
                RightTriggerUp   = RightTrigger == 0;
                RightTriggerDown = prevVal < _downThreshold && RightTrigger >= _downThreshold;

                // While OculusUsages.indexTouch is recommended, only CommonUsages.indexTouch is currently providing proper values
                LeftTriggerNear = getFeatureUsage(primaryLeftController, CommonUsages.indexTouch) > 0;
                LeftThumbNear   = getFeatureUsage(primaryLeftController, CommonUsages.thumbTouch) > 0;

#if USING_XR_SDK
                LeftThumbNear = getFeatureUsage(primaryLeftController, OculusUsages.indexTouch) > 0;
#endif

#if USING_COMPATIBLE_OCULUS_XR_PLUGIN_VERSION
                LeftThumbNear = getFeatureUsage(primaryLeftController, OculusUsages.indexTouch) > 0;
#endif

                RightTriggerNear = getFeatureUsage(primaryRightController, CommonUsages.indexTouch) > 0;
                RightThumbNear   = getFeatureUsage(primaryRightController, CommonUsages.thumbTouch) > 0;



                prevBool    = AButton;
                AButton     = getFeatureUsage(primaryRightController, CommonUsages.primaryButton);
                AButtonDown = prevBool == false && AButton == true;
                AButtonUp   = prevBool == true && AButton == false;

                prevBool    = BButton;
                BButton     = getFeatureUsage(primaryRightController, CommonUsages.secondaryButton);
                BButtonDown = prevBool == false && BButton == true;
                BButtonUp   = prevBool == true && BButton == false;

                prevBool    = XButton;
                XButton     = getFeatureUsage(primaryLeftController, CommonUsages.primaryButton);
                XButtonDown = prevBool == false && XButton == true;
                XButtonUp   = prevBool == true && XButton == false;

                prevBool    = YButton;
                YButton     = getFeatureUsage(primaryLeftController, CommonUsages.secondaryButton);
                YButtonDown = prevBool == false && YButton == true;
                YButtonUp   = prevBool == true && YButton == false;

                prevBool        = StartButton;
                StartButton     = getFeatureUsage(primaryRightController, CommonUsages.menuButton);
                StartButtonDown = prevBool == false && StartButton == true;

                prevBool       = BackButton;
                BackButton     = getFeatureUsage(primaryLeftController, CommonUsages.menuButton);
                BackButtonDown = prevBool == false && BackButton == true;
#endif
            }

            // Call events
            OnInputsUpdated?.Invoke();
        }
Пример #28
0
        public sealed override void BeforeRenderUpdate()
        {
            if (knownActiveInputSubsystem == VRModuleKnownXRInputSubsystem.Unknown)
            {
                knownActiveInputSubsystem = GetKnownActiveInputSubsystem();
            }

            // update device connection and poses
            IVRModuleDeviceState   prevState;
            IVRModuleDeviceStateRW currState;
            uint deviceIndex;

            FlushDeviceState();

            // mark all devices as disconnected
            // therefore, if a device should stay alive in this frame
            // should be set as connected in the next stage
            deviceIndex = 0u;
            for (var len = GetDeviceStateLength(); deviceIndex < len; ++deviceIndex)
            {
                if (TryGetValidDeviceState(deviceIndex, out prevState, out currState))
                {
                    currState.isConnected = false;
                }
            }

            InputDevices.GetDevices(connectedDevices);

            foreach (var device in connectedDevices)
            {
                if (!indexMap.TryGetIndex(device, out deviceIndex))
                {
                    if (indexMap.TryMapAsHMD(device))
                    {
                        deviceIndex = VRModule.HMD_DEVICE_INDEX;
                        EnsureValidDeviceState(deviceIndex, out prevState, out currState);
                    }
                    else
                    {
                        // this function will skip VRModule.HMD_DEVICE_INDEX (preserved index for HMD)
                        deviceIndex = FindAndEnsureUnusedNotHMDDeviceState(out prevState, out currState);
                        indexMap.MapNonHMD(device, deviceIndex);
                    }

                    currState.deviceClass     = GetDeviceClass(device.name, device.characteristics);
                    currState.serialNumber    = device.name + " " + device.serialNumber + " " + (int)device.characteristics;
                    currState.modelNumber     = device.name + " (" + device.characteristics + ")";
                    currState.renderModelName = device.name + " (" + device.characteristics + ")";

                    SetupKnownDeviceModel(currState);

                    Debug.LogFormat("Device connected: {0} / {1} / {2} / {3} / {4} / {5} ({6})",
                                    currState.deviceIndex,
                                    currState.deviceClass,
                                    currState.deviceModel,
                                    currState.modelNumber,
                                    currState.serialNumber,
                                    device.name,
                                    device.characteristics);

                    if ((device.characteristics & InputDeviceCharacteristics.Right) > 0u)
                    {
                        uxrRightIndex = deviceIndex;
                    }
                    else if ((device.characteristics & InputDeviceCharacteristics.Left) > 0u)
                    {
                        uxrLeftIndex = deviceIndex;
                    }

                    UpdateNewConnectedInputDevice(currState, device);
                }
                else
                {
                    EnsureValidDeviceState(deviceIndex, out prevState, out currState);
                }
                currState.isConnected = true;
                // update device Poses
                currState.isPoseValid     = GetDeviceFeatureValueOrDefault(device, CommonUsages.isTracked);
                currState.position        = GetDeviceFeatureValueOrDefault(device, CommonUsages.devicePosition);
                currState.rotation        = GetDeviceFeatureValueOrDefault(device, CommonUsages.deviceRotation);
                currState.velocity        = GetDeviceFeatureValueOrDefault(device, CommonUsages.deviceVelocity);
                currState.angularVelocity = GetDeviceFeatureValueOrDefault(device, CommonUsages.deviceAngularVelocity);

                // TODO: update hand skeleton pose
            }

            // unmap index for disconnected device state
            deviceIndex = 0u;
            for (var len = GetDeviceStateLength(); deviceIndex < len; ++deviceIndex)
            {
                if (indexMap.IsMapped(deviceIndex))
                {
                    EnsureValidDeviceState(deviceIndex, out prevState, out currState);
                    if (prevState.isConnected && !currState.isConnected)
                    {
                        indexMap.UnmapByIndex(deviceIndex);
                        currState.Reset();
                        if (uxrRightIndex == deviceIndex)
                        {
                            uxrRightIndex = INVALID_DEVICE_INDEX;
                        }
                        if (uxrLeftIndex == deviceIndex)
                        {
                            uxrLeftIndex = INVALID_DEVICE_INDEX;
                        }
                    }
                }
            }

            submodules.UpdateModulesDeviceConnectionAndPoses();

            // process hand role
            var subRightIndex = submodules.GetFirstRightHandedIndex();
            var currentRight  = (subRightIndex == INVALID_DEVICE_INDEX || (TryGetValidDeviceState(uxrRightIndex, out prevState, out currState) && currState.isPoseValid)) ? uxrRightIndex : subRightIndex;
            var subLeftIndex  = submodules.GetFirstLeftHandedIndex();
            var currentLeft   = (subLeftIndex == INVALID_DEVICE_INDEX || (TryGetValidDeviceState(uxrLeftIndex, out prevState, out currState) && currState.isPoseValid)) ? uxrLeftIndex : subLeftIndex;
            var roleChanged   = ChangeProp.Set(ref moduleRightIndex, currentRight);

            roleChanged |= ChangeProp.Set(ref moduleLeftIndex, currentLeft);

            if (roleChanged)
            {
                InvokeControllerRoleChangedEvent();
            }

            ProcessConnectedDeviceChanged();
            ProcessDevicePoseChanged();
        }
 void GetDevice()
 {
     InputDevices.GetDevicesAtXRNode(XRNode, devices);
     device = devices.FirstOrDefault();
 }
Пример #30
0
    // Update is called once per frame
    void Update()   //checks controller state and implements jumping mechanics
    {
        InputDevice device = InputDevices.GetDeviceAtXRNode(inputSource);

        device.TryGetFeatureValue(CommonUsages.primary2DAxis, out inputAxis);       //not sure if this will help or not

        //buttonPressEvent
        device.TryGetFeatureValue(CommonUsages.triggerButton, out isTrigger);
        device.TryGetFeatureValue(CommonUsages.primaryButton, out jumpPressed);
        if (isTrigger)
        {
            if (isTriggerHeld)
            {
                // ButtonHeldEvent.Invoke();
            }
            else
            {
                isTriggerHeld = true;
                //ButtonDownEvent.Invoke();
            }
        }
        else
        {
            //ButtonUpEvent.Invoke();
            isTriggerHeld = false;
        }

        if (jumpPressed)// && ContinuousMovement.isGrounded)
        {
            if (PController.isGrounded && !jumpHeld)
            {
                jumpHeld = true;
                print("jump");
                PController.isJumping = true;
                // this.GetComponent<PController>().SuspendGroundCheck();
                //Vector3 jumpDir = (this.transform.position - prevPos).normalized;             //doesn't work....

                //this block is for properly scaling jump in all directions, the physics calculations made this difficult to figure out
                float   force          = jumpForce;
                Vector2 inputDirection = this.GetComponent <PController>().GetLeftAxis();

                /* if (inputDirection.x > 0)
                 * {
                 *   force = jumpForce / 2;
                 * }
                 * else if (inputDirection.x < 0)
                 * {
                 *   force = jumpForce / 2;
                 * }
                 * else
                 *   force = jumpForce; */

                if (inputDirection.y < 0)
                {
                    force = jumpForce;
                }
                if (inputDirection.y > 0)
                {
                    force = jumpForce * 1.5f;
                }

                this.GetComponent <Rigidbody>().AddForce((transform.up).normalized * force);


                //this block dictates where to put extra momentum for some extra direction in the jump
                Vector3 jumpDir = new Vector3(0, 0, 0);
                if (inputDirection.x > 0)
                {
                    if (inputDirection.y > 0)
                    {
                        jumpDir = (this.transform.forward + this.transform.right).normalized;
                    }
                    else if (inputDirection.y < 0)
                    {
                        jumpDir = (this.transform.forward - this.transform.right).normalized;
                    }
                    else
                    {
                        jumpDir = this.transform.forward.normalized;
                    }
                }
                else if (inputDirection.x < 0)
                {
                    if (inputDirection.y > 0)
                    {
                        jumpDir = (-this.transform.forward + this.transform.right).normalized;
                    }
                    else if (inputDirection.y < 0)
                    {
                        jumpDir = (-this.transform.forward - this.transform.right).normalized;
                    }
                    else
                    {
                        jumpDir = -this.transform.forward.normalized;
                    }
                }
                else
                {
                    if (inputDirection.y > 0)
                    {
                        jumpDir = (this.transform.right).normalized;
                    }
                    else if (inputDirection.y < 0)
                    {
                        jumpDir = (-this.transform.right).normalized;
                    }
                }

                this.GetComponent <Rigidbody>().AddForce(jumpDir * jumpForce / 10);                //adds a bit of directional momentum
            }
        }
        else
        {
            jumpHeld = false;
        }
    }
Пример #31
0
 public ControlScheme(InputDevices inputDevice, string deviceName, float deadZone)
 {
     m_InputDevice = inputDevice;
     m_DeviceName = deviceName;
     m_DeadZone = deadZone;
 }