GetLocalControllerRotation() public static method

Gets the rotation of the given Controller local to its tracking space. Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity.
public static GetLocalControllerRotation ( OVRInput, controllerType ) : Quaternion
controllerType OVRInput,
return Quaternion
    // Update is called once per frame
    void Update()
    {
        // Update position and rotation of the controller
        gameObject.transform.localPosition = OVRInput.GetLocalControllerPosition(handType);
        gameObject.transform.localRotation = OVRInput.GetLocalControllerRotation(handType);

        OVRInput.Update();

        // Detect events
        #region Start button

        if (OVRInput.Get(OVRInput.Button.Start))
        {
            Debug.Log("Start button pressed");
        }

        #endregion

        #region Button A and X

        // Returns true if the primary button (typically “A”) was pressed this frame
        if (OVRInput.GetDown(OVRInput.Button.One, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button X Down");
            }
            else
            {
                Debug.Log("Button A Down");
            }
        }

        // Returns true if the primary button (typically “A”) is currently pressed
        if (OVRInput.Get(OVRInput.Button.One, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button X Pressed");
            }
            else
            {
                Debug.Log("Button A Pressed");
            }
        }

        // Returns true if the primary button (typically “A”) is released
        if (OVRInput.GetUp(OVRInput.Button.One, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button X up");
            }
            else
            {
                Debug.Log("Button A up");
            }
        }

        // Returns true if the primary button is touched
        if (OVRInput.Get(OVRInput.Touch.One, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button X touched");
            }
            else
            {
                Debug.Log("Button A touched");
            }
        }

        #endregion

        #region Button B and Y

        // Returns true if the secondary button (typically “B”) was pressed this frame
        if (OVRInput.GetDown(OVRInput.Button.Two, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button Y down");
            }
            else
            {
                Debug.Log("Button B down");
            }
        }

        // Returns true if the secondary button (typically “B”) is currently pressed
        if (OVRInput.Get(OVRInput.Button.Two, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button Y pressed");
            }
            else
            {
                Debug.Log("Button B pressed");
            }
        }

        // Returns true if the secondary button (typically “B”) is released
        if (OVRInput.GetUp(OVRInput.Button.Two, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button Y up");
            }
            else
            {
                Debug.Log("Button B up");
            }
        }

        // Returns true if the primary button is touched
        if (OVRInput.Get(OVRInput.Touch.Two, handType))
        {
            if (handType == OVRInput.Controller.LTouch)
            {
                Debug.Log("Button Y touched");
            }
            else
            {
                Debug.Log("Button B touched");
            }
        }

        #endregion

        #region Triggers

        // Returns a float of the left index finger trigger’s current state.
        // (range of 0.0f to 1.0f)
        if (OVRInput.Get(OVRInput.RawAxis1D.LIndexTrigger) > 0f)
        {
            Debug.Log("Left index trigger: " + OVRInput.Get(OVRInput.RawAxis1D.LIndexTrigger));
        }

        if (OVRInput.Get(OVRInput.RawAxis1D.LHandTrigger) > 0f)
        {
            Debug.Log("Left hand trigger: " + OVRInput.Get(OVRInput.RawAxis1D.LHandTrigger));
        }

        if (OVRInput.Get(OVRInput.RawAxis1D.RIndexTrigger) > 0f)
        {
            Debug.Log("Right index trigger: " + OVRInput.Get(OVRInput.RawAxis1D.RIndexTrigger));
        }

        if (OVRInput.Get(OVRInput.RawAxis1D.RHandTrigger) > 0f)
        {
            Debug.Log("Right hand trigger: " + OVRInput.Get(OVRInput.RawAxis1D.RHandTrigger));
        }

        // Trigger touch
        if (OVRInput.Get(OVRInput.Touch.PrimaryIndexTrigger))
        {
            Debug.Log("Left index trigger touched");
        }

        if (OVRInput.Get(OVRInput.Touch.SecondaryIndexTrigger))
        {
            Debug.Log("Right index trigger touched");
        }

        #endregion

        #region Thumbsticks

        // Returns true if the primary thumbstick has been moved upwards more than halfway.
        // (Up/Down/Left/Right - Interpret the thumbstick as a D-pad).
        if (OVRInput.Get(OVRInput.Button.PrimaryThumbstickDown))
        {
            Debug.Log("Left thumbstick down");
        }

        // Returns true if the primary thumbstick is currently pressed (clicked as a button)
        if (OVRInput.Get(OVRInput.Button.PrimaryThumbstick))
        {
            Vector2 coordinates = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);

            Debug.Log("Left thumbstick pressed: x: " + coordinates.x
                      + " / y: " + coordinates.y);
        }

        // Returns true if the primary thumbstick has been moved upwards more than halfway.
        // (Up/Down/Left/Right - Interpret the thumbstick as a D-pad).
        if (OVRInput.Get(OVRInput.Button.PrimaryThumbstickUp))
        {
            Debug.Log("Right thumbstick up");
        }

        // Returns true if the secondary thumbstick has been moved upwards more than halfway.
        // (Up/Down/Left/Right - Interpret the thumbstick as a D-pad).
        if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickDown))
        {
            Debug.Log("Right thumbstick down");
        }

        // Returns true if the secondary thumbstick is currently pressed (clicked as a button)
        if (OVRInput.Get(OVRInput.Button.SecondaryThumbstick))
        {
            Vector2 coordinates = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);

            Debug.Log("Right thumbstick pressed: x: " + coordinates.x
                      + " / y: " + coordinates.y);
        }

        // Returns true if the secondary thumbstick has been moved upwards more than halfway.
        // (Up/Down/Left/Right - Interpret the thumbstick as a D-pad).
        if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickUp))
        {
            Debug.Log("Right thumbstick up");
        }

        // Thumbsticks touch
        if (OVRInput.Get(OVRInput.Touch.PrimaryThumbstick))
        {
            Debug.Log("Left thumbstick touched");
        }

        if (OVRInput.Get(OVRInput.Touch.SecondaryThumbstick))
        {
            Debug.Log("Right thumbstick touched");
        }

        #endregion

        #region Thumbrest

        // Thumb rest touch
        if (OVRInput.Get(OVRInput.Touch.PrimaryThumbRest))
        {
            Debug.Log("Left thumb rest touched");
        }

        if (OVRInput.Get(OVRInput.Touch.SecondaryThumbRest))
        {
            Debug.Log("Right thumb rest touched");
        }

        #endregion
    }
示例#2
0
 // Helper function to get the controller's world rotation
 private Quaternion getWorldRotation(OVRInput.Controller hand)
 {
     return(GetObjects.instance.getPlayer().gameObject.transform.parent.rotation *OVRInput.GetLocalControllerRotation(hand));
 }
    public void GrabEnd()
    {
        EVRA_Grabber otherGrabberRef = m_OtherGrabVolume;

        RemoveOtherGrabVolume();

        if (!m_grabbed)
        {
            return;               // If no objects currently grabbed, end quickly
        }
        // There are two situations:
        // 1) the grabbed object has only one hand grabbing it (aka this one)
        // 2) the grabbed object has two hands grabbing it

        // 1) We need to call `GrabEnd()` with the appropriate linear and angular velocity
        // 2) We need to switch parenting over to the other hand via `SwitchHand()`. To tell if there is another grab volume grabbing the object, we just check if m_OtherGrabVolume is not null

        if (otherGrabberRef)
        {
            // If we have an other grabber ref, then that means that multiple objects are holding the current item.
            // Now, technically, it can be either the initial holder of the item or the rotation ref.
            // If it's the initial holder, then we let go AND transfer possession to the other grab volume
            // If it's just the rotation ref, then we just need to decouple the other grab volume - we don't need to let go of it.
            if (m_grabbed.GrabbableRef.currentGrabber == this)
            {
                //otherGrabberRef.transform.localRotation = Quaternion.Euler(0f,0f,0f);
                m_grabbed.GrabbableRef.SwitchHand(otherGrabberRef);
                //m_grabbed.GrabbableRef.GrabEnd();
            }
            otherGrabberRef.RemoveOtherGrabVolume();
            //if (m_grabbed.GrabbableRef.currentGrabber.grabbed != m_grabbed) m_grabbed.GrabbableRef.currentGrabber.RemoveOtherGrabVolume();
        }
        else
        {
            OVRPose localPose = new OVRPose {
                position = OVRInput.GetLocalControllerPosition(m_CustomGrabber.OVRController), orientation = OVRInput.GetLocalControllerRotation(m_CustomGrabber.OVRController)
            };
            OVRPose trackingSpace   = transform.ToOVRPose() * localPose.Inverse();
            Vector3 linearVelocity  = trackingSpace.orientation * OVRInput.GetLocalControllerVelocity(m_CustomGrabber.OVRController);
            Vector3 angularVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerAngularVelocity(m_CustomGrabber.OVRController);
            angularVelocity *= -1;
            m_grabbed.GrabbableRef.GrabEnd(linearVelocity, angularVelocity);
            //m_grabbed.GrabbableRef.currentGrabber.RemoveOtherGrabVolume();
        }

        /*
         * if (m_grabbed.GrabbableRef.currentGrabber && m_grabbed.GrabbableRef.currentGrabber.OtherGrabVolume) {
         *  if (m_grabbed.GrabbableRef.currentGrabber.grabbed && m_grabbed.GrabbableRef.currentGrabber.grabbed != m_grabbed) m_grabbed.GrabbableRef.currentGrabber.RemoveOtherGrabVolume();
         * }
         * if (m_grabbed.GrabbableRef.currentGrabber == this) {
         *  OVRPose localPose = new OVRPose { position = OVRInput.GetLocalControllerPosition(m_CustomGrabber.OVRController), orientation = OVRInput.GetLocalControllerRotation(m_CustomGrabber.OVRController) };
         *  OVRPose trackingSpace = transform.ToOVRPose() * localPose.Inverse();
         *  Vector3 linearVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerVelocity(m_CustomGrabber.OVRController);
         *  Vector3 angularVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerAngularVelocity(m_CustomGrabber.OVRController);
         *  angularVelocity *= -1;
         *  m_grabbed.GrabbableRef.GrabEnd(linearVelocity,angularVelocity);
         * }
         */
        transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
        m_grabbed = null;
    }
示例#4
0
    protected virtual void UpdateAnchors(bool updateEyeAnchors, bool updateHandAnchors)
    {
        if (!OVRManager.OVRManagerinitialized)
        {
            return;
        }

        EnsureGameObjectIntegrity();

        if (!Application.isPlaying)
        {
            return;
        }

        if (_skipUpdate)
        {
            centerEyeAnchor.FromOVRPose(OVRPose.identity, true);
            leftEyeAnchor.FromOVRPose(OVRPose.identity, true);
            rightEyeAnchor.FromOVRPose(OVRPose.identity, true);

            return;
        }

        bool monoscopic = OVRManager.instance.monoscopic;
        bool hmdPresent = OVRNodeStateProperties.IsHmdPresent();

        OVRPose tracker = OVRManager.tracker.GetPose();

        trackerAnchor.localRotation = tracker.orientation;

        Quaternion emulatedRotation = Quaternion.Euler(-OVRManager.instance.headPoseRelativeOffsetRotation.x, -OVRManager.instance.headPoseRelativeOffsetRotation.y, OVRManager.instance.headPoseRelativeOffsetRotation.z);

        //Note: in the below code, when using UnityEngine's API, we only update anchor transforms if we have a new, fresh value this frame.
        //If we don't, it could mean that tracking is lost, etc. so the pose should not change in the virtual world.
        //This can be thought of as similar to calling InputTracking GetLocalPosition and Rotation, but only for doing so when the pose is valid.
        //If false is returned for any of these calls, then a new pose is not valid and thus should not be updated.
        if (updateEyeAnchors)
        {
            if (hmdPresent)
            {
                Vector3    centerEyePosition = Vector3.zero;
                Quaternion centerEyeRotation = Quaternion.identity;

                if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.CenterEye, NodeStatePropertyType.Position, OVRPlugin.Node.EyeCenter, OVRPlugin.Step.Render, out centerEyePosition))
                {
                    centerEyeAnchor.localPosition = centerEyePosition;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.CenterEye, NodeStatePropertyType.Orientation, OVRPlugin.Node.EyeCenter, OVRPlugin.Step.Render, out centerEyeRotation))
                {
                    centerEyeAnchor.localRotation = centerEyeRotation;
                }
            }
            else
            {
                centerEyeAnchor.localRotation = emulatedRotation;
                centerEyeAnchor.localPosition = OVRManager.instance.headPoseRelativeOffsetTranslation;
            }

            if (!hmdPresent || monoscopic)
            {
                leftEyeAnchor.localPosition  = centerEyeAnchor.localPosition;
                rightEyeAnchor.localPosition = centerEyeAnchor.localPosition;
                leftEyeAnchor.localRotation  = centerEyeAnchor.localRotation;
                rightEyeAnchor.localRotation = centerEyeAnchor.localRotation;
            }
            else
            {
                Vector3    leftEyePosition  = Vector3.zero;
                Vector3    rightEyePosition = Vector3.zero;
                Quaternion leftEyeRotation  = Quaternion.identity;
                Quaternion rightEyeRotation = Quaternion.identity;

                if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.LeftEye, NodeStatePropertyType.Position, OVRPlugin.Node.EyeLeft, OVRPlugin.Step.Render, out leftEyePosition))
                {
                    leftEyeAnchor.localPosition = leftEyePosition;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.RightEye, NodeStatePropertyType.Position, OVRPlugin.Node.EyeRight, OVRPlugin.Step.Render, out rightEyePosition))
                {
                    rightEyeAnchor.localPosition = rightEyePosition;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.LeftEye, NodeStatePropertyType.Orientation, OVRPlugin.Node.EyeLeft, OVRPlugin.Step.Render, out leftEyeRotation))
                {
                    leftEyeAnchor.localRotation = leftEyeRotation;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.RightEye, NodeStatePropertyType.Orientation, OVRPlugin.Node.EyeRight, OVRPlugin.Step.Render, out rightEyeRotation))
                {
                    rightEyeAnchor.localRotation = rightEyeRotation;
                }
            }
        }

        if (updateHandAnchors)
        {
            //Need this for controller offset because if we're on OpenVR, we want to set the local poses as specified by Unity, but if we're not, OVRInput local position is the right anchor
            if (OVRManager.loadedXRDevice == OVRManager.XRDevice.OpenVR)
            {
                Vector3    leftPos   = Vector3.zero;
                Vector3    rightPos  = Vector3.zero;
                Quaternion leftQuat  = Quaternion.identity;
                Quaternion rightQuat = Quaternion.identity;

                if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.LeftHand, NodeStatePropertyType.Position, OVRPlugin.Node.HandLeft, OVRPlugin.Step.Render, out leftPos))
                {
                    leftHandAnchor.localPosition = leftPos;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyVector3(Node.RightHand, NodeStatePropertyType.Position, OVRPlugin.Node.HandRight, OVRPlugin.Step.Render, out rightPos))
                {
                    rightHandAnchor.localPosition = rightPos;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.LeftHand, NodeStatePropertyType.Orientation, OVRPlugin.Node.HandLeft, OVRPlugin.Step.Render, out leftQuat))
                {
                    leftHandAnchor.localRotation = leftQuat;
                }
                if (OVRNodeStateProperties.GetNodeStatePropertyQuaternion(Node.RightHand, NodeStatePropertyType.Orientation, OVRPlugin.Node.HandRight, OVRPlugin.Step.Render, out rightQuat))
                {
                    rightHandAnchor.localRotation = rightQuat;
                }
            }
            else
            {
                leftHandAnchor.localPosition  = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch);
                rightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch);
                leftHandAnchor.localRotation  = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch);
                rightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch);
            }

            trackerAnchor.localPosition = tracker.position;

            OVRPose leftOffsetPose  = OVRPose.identity;
            OVRPose rightOffsetPose = OVRPose.identity;
            if (OVRManager.loadedXRDevice == OVRManager.XRDevice.OpenVR)
            {
                leftOffsetPose  = OVRManager.GetOpenVRControllerOffset(Node.LeftHand);
                rightOffsetPose = OVRManager.GetOpenVRControllerOffset(Node.RightHand);

                //Sets poses of left and right nodes, local to the tracking space.
                OVRManager.SetOpenVRLocalPose(trackingSpace.InverseTransformPoint(leftControllerAnchor.position),
                                              trackingSpace.InverseTransformPoint(rightControllerAnchor.position),
                                              Quaternion.Inverse(trackingSpace.rotation) * leftControllerAnchor.rotation,
                                              Quaternion.Inverse(trackingSpace.rotation) * rightControllerAnchor.rotation);
            }
            rightControllerAnchor.localPosition = rightOffsetPose.position;
            rightControllerAnchor.localRotation = rightOffsetPose.orientation;
            leftControllerAnchor.localPosition  = leftOffsetPose.position;
            leftControllerAnchor.localRotation  = leftOffsetPose.orientation;
        }

        RaiseUpdatedAnchorsEvent();
    }
示例#5
0
    protected virtual void UpdateAnchors()
    {
        EnsureGameObjectIntegrity();

        if (!Application.isPlaying)
        {
            return;
        }

        if (_skipUpdate)
        {
            centerEyeAnchor.FromOVRPose(OVRPose.identity, true);
            leftEyeAnchor.FromOVRPose(OVRPose.identity, true);
            rightEyeAnchor.FromOVRPose(OVRPose.identity, true);

            return;
        }

        bool monoscopic = OVRManager.instance.monoscopic;
        bool hmdPresent = OVRNodeStateProperties.IsHmdPresent();

        OVRPose tracker = OVRManager.tracker.GetPose();

        trackerAnchor.localRotation = tracker.orientation;

        Quaternion emulatedRotation = Quaternion.Euler(-OVRManager.instance.headPoseRelativeOffsetRotation.x, -OVRManager.instance.headPoseRelativeOffsetRotation.y, OVRManager.instance.headPoseRelativeOffsetRotation.z);

        centerEyeAnchor.localRotation = hmdPresent ? InputTracking.GetLocalRotation(Node.CenterEye) : emulatedRotation;
        leftEyeAnchor.localRotation   = (!hmdPresent || monoscopic) ? centerEyeAnchor.localRotation : InputTracking.GetLocalRotation(Node.LeftEye);
        rightEyeAnchor.localRotation  = (!hmdPresent || monoscopic) ? centerEyeAnchor.localRotation : InputTracking.GetLocalRotation(Node.RightEye);

        //Need this for controller offset because if we're on OpenVR, we want to set the local poses as specified by Unity, but if we're not, OVRInput local position is the right anchor
        if (OVRManager.loadedXRDevice == OVRManager.XRDevice.OpenVR)
        {
            leftHandAnchor.localPosition  = InputTracking.GetLocalPosition(Node.LeftHand);
            rightHandAnchor.localPosition = InputTracking.GetLocalPosition(Node.RightHand);
            leftHandAnchor.localRotation  = InputTracking.GetLocalRotation(Node.LeftHand);
            rightHandAnchor.localRotation = InputTracking.GetLocalRotation(Node.RightHand);
        }
        else
        {
            leftHandAnchor.localPosition  = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch);
            rightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch);
            leftHandAnchor.localRotation  = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch);
            rightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch);
        }

        trackerAnchor.localPosition = tracker.position;

        centerEyeAnchor.localPosition = hmdPresent ? InputTracking.GetLocalPosition(Node.CenterEye) : OVRManager.instance.headPoseRelativeOffsetTranslation;
        leftEyeAnchor.localPosition   = (!hmdPresent || monoscopic) ? centerEyeAnchor.localPosition : InputTracking.GetLocalPosition(Node.LeftEye);
        rightEyeAnchor.localPosition  = (!hmdPresent || monoscopic) ? centerEyeAnchor.localPosition : InputTracking.GetLocalPosition(Node.RightEye);

        OVRPose leftOffsetPose  = OVRPose.identity;
        OVRPose rightOffsetPose = OVRPose.identity;

        if (OVRManager.loadedXRDevice == OVRManager.XRDevice.OpenVR)
        {
            leftOffsetPose  = OVRManager.GetOpenVRControllerOffset(Node.LeftHand);
            rightOffsetPose = OVRManager.GetOpenVRControllerOffset(Node.RightHand);

            //Sets poses of left and right nodes, local to the tracking space.
            OVRManager.SetOpenVRLocalPose(trackingSpace.InverseTransformPoint(leftControllerAnchor.position),
                                          trackingSpace.InverseTransformPoint(rightControllerAnchor.position),
                                          Quaternion.Inverse(trackingSpace.rotation) * leftControllerAnchor.rotation,
                                          Quaternion.Inverse(trackingSpace.rotation) * rightControllerAnchor.rotation);
        }
        rightControllerAnchor.localPosition = rightOffsetPose.position;
        rightControllerAnchor.localRotation = rightOffsetPose.orientation;
        leftControllerAnchor.localPosition  = leftOffsetPose.position;
        leftControllerAnchor.localRotation  = leftOffsetPose.orientation;

        RaiseUpdatedAnchorsEvent();
    }
    // Update is called once per frame
    void Update()
    {
        //We are creating a variable to hold the active controller
        OVRInput.Controller activeController = OVRInput.GetActiveController();

        //We are setting the position of the ray to the calculated position of the
        //active controller (it's not tracked but an estimate is hold)
        transform.localPosition = OVRInput.GetLocalControllerPosition(activeController);

        //We are setting the rotation of the ray to the rotation of the active controller
        transform.rotation = OVRInput.GetLocalControllerRotation(activeController);

        if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger))
        {
            RaycastHit hitInfo;
            if (Physics.Raycast(new Ray(transform.position, transform.forward), out hitInfo))
            {
                //We are using a Tag named Grabbable (set on the Inspector View for the Cube
                //and the Sphere) to not take into account hits with other objects (table etc.)
                if (hitInfo.transform.tag == "Grabbable")
                {
                    isGrabbing = true;

                    //We are getting the transform value of the hit object
                    grabbedTransform = hitInfo.transform;

                    //We are setting isKinematic as true and useGravity as falseso that we can
                    //control the object via controller, as if it was stuck to it
                    grabbedTransform.GetComponent <Rigidbody>().isKinematic = true;
                    grabbedTransform.GetComponent <Rigidbody>().useGravity  = false;

                    //We are declaring that the Hand object (to which this script is attached)
                    //is the parent of the hit object (Cube or Sphere in this case)
                    //So that we can control its movement
                    grabbedTransform.parent = transform;
                }
            }
        }

        if (OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger))
        {
            //We are reversing the isKinematic and useGravity settings so that
            //the object can move independent of the Hand
            grabbedTransform.GetComponent <Rigidbody>().isKinematic = false;
            grabbedTransform.GetComponent <Rigidbody>().useGravity  = true;

            //We are setting the parent as none so that the Hand object
            //no longer controls the movement for this object
            grabbedTransform.parent = null;
            isGrabbing = false;
        }


        if (isGrabbing)
        {
            //We are moving the grabbed object in its local z-axis to cater for
            //the lack of position tracking in Oculus Go controller
            float distance = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad).y;

            //We can adjust the speed with the zSpeed variable
            grabbedTransform.position += distance * Time.deltaTime * zSpeed * transform.forward;
        }
    }
        /// <summary>
        /// Function will emit a raycast from the camera or controller. It will set <c>m_Target</c> to the current object being raycast on.
        /// Inside this function is also where the events are triggered and objects are interacted with (held/thrown/clicked on).
        /// </summary>
        private void Raycast()
        {
            // Show the debug ray if required
            if (m_ShowDebugRay)
            {
                Debug.DrawRay(m_Camera.position, m_Camera.forward * m_DebugRayLength, Color.blue, m_DebugRayDuration);
            }

            // Create a ray that points forwards from the camera.
            Ray        ray = new Ray(m_Camera.position, m_Camera.forward);
            RaycastHit hit;

            Vector3 worldStartPoint = Vector3.zero;
            Vector3 worldEndPoint   = Vector3.zero;

            // If the controller is connected and we are past Scene 1, emit the raycast from the controller instead of the camera
            if (ControllerIsConnected && m_TrackingSpace != null && IntroSessionManager.s_Instance.GetCurrentScene() > 1)
            {
                if (!m_ControllerModel.activeSelf)
                {
                    m_ControllerModel.SetActive(true);
                }
                m_ControllerModel.SetActive(true);
                Matrix4x4  localToWorld = m_TrackingSpace.localToWorldMatrix;
                Quaternion orientation  = OVRInput.GetLocalControllerRotation(Controller);

                Vector3 localStartPoint = OVRInput.GetLocalControllerPosition(Controller);
                Vector3 localEndPoint   = localStartPoint + ((orientation * Vector3.forward) * 500.0f);

                worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
                worldEndPoint   = localToWorld.MultiplyPoint(localEndPoint);

                // Create new ray
                ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
            }

            // Do the raycast forwards to see if we hit an interactive item
            if (Physics.Raycast(ray, out hit, m_RayLength, ~m_ExclusionLayers))
            {
                m_Target = hit.collider.gameObject;       // the target hit by the raycast

                m_OffsetVector = m_Target.transform.position - OVRInput.GetLocalControllerPosition(Controller);


                // Check if the reticle is in an interacting state
                if (m_CurrentReticleState == ReticleState.InteractingState && !m_HoldingObject)
                {
                    m_ReticleStateTimer += Time.deltaTime;
                    if (m_ReticleStateTimer >= 0.5f)
                    {
                        // Timer is finished, revert back to default
                        IntroSessionManager.s_Instance.ReticleSetDefaultState();
                        m_CurrentReticleState = ReticleState.DefaultState;
                        m_ReticleStateTimer   = 0;
                    }
                }


                // check to see if the raycast is hitting anything we can interact with and was not already aiming at one
                if (m_Target.tag.Contains("_Interactable_"))
                {
                    // Target is interactable

                    if (!m_OverrideDefaultReticleControls)
                    {
                        if (m_CurrentReticleState == ReticleState.DefaultState)
                        {
                            // The reticle is in its default state on the current frame
                            // so put the reticle in a hover state.
                            IntroSessionManager.s_Instance.ReticleSetHoverState();
                            m_CurrentReticleState = ReticleState.HoverState;
                        }
                    }

                    // Check in here for trigger being pulled
                    if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger))
                    {
                        // Add code here to check if user clicks the trigger while targeting an object
                        IntroSessionManager.s_Instance.ReticleSetInteracting(); // Set the reticle to its interacting state
                        m_CurrentReticleState = ReticleState.InteractingState;

                        //if (m_Target.tag.Contains("_EnterTagOnObjectHere_"))


                        if (m_Target.tag.Contains("_Stage3Button_"))
                        {
                            // User clicked on the button
                            AudioSource buttonSound = m_Target.GetComponent <AudioSource>();
                            if (buttonSound != null)
                            {
                                buttonSound.Play();
                            }

                            // Notify any subscribers that the button has been clicked.
                            if (e_ButtonClicked != null)
                            {
                                e_ButtonClicked();
                            }
                        } // End checking for Stage3Button
                    }   // End checking when user pulled trigger
                }
                else
                {
                    // The target is not interactable
                    if (m_CurrentReticleState == ReticleState.HoverState && !m_OverrideDefaultReticleControls)
                    {
                        // On this frame the user is not looking targeting/interacting with an interactable object and the user was on the last frame
                        // Set the reticle state to default
                        IntroSessionManager.s_Instance.ReticleSetDefaultState();
                        m_CurrentReticleState = ReticleState.DefaultState;
                    }
                }


                if (m_ObjectHeld)
                {
                    // Currently holding an object
                    if (OVRInput.GetDown(OVRInput.Button.DpadUp) || OVRInput.GetDown(OVRInput.Button.DpadLeft) || OVRInput.GetDown(OVRInput.Button.DpadRight))
                    {
                        // User swiped, throw ball forward. This works if the user swipes up, left, or right. We found this made it easier for the user to throw the ball forward
                        ThrowObject(1);
                    }
                    else if (OVRInput.GetDown(OVRInput.Button.DpadDown))
                    {
                        // User swiped down, throw ball backwards (towards the user)
                        ThrowObject(-1);
                    }
                    if (!OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger))
                    {
                        //Trigger button is released
                        ReleaseObject();
                        m_ObjectReleased = true;
                    }
                }
                else
                {
                    // not currently holding an object
                    if (OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger))
                    {
                        // User pulled the trigger in
                        if (m_Target.tag.Contains("_PickUp_"))
                        {
                            // object being aimed at can be picked up
                            if (m_ObjectReleased)
                            {
                                // User has released the trigger since the last time and now held the trigger down (for this frame). Pick up the object
                                m_ObjectHeld = m_Target;
                                GrabObject();
                                m_ObjectReleased = false;
                            }
                        }
                    }
                    else
                    {
                        // User is not pressing the trigger
                        m_ObjectReleased = true;
                    }
                }

                // Something was hit, set at the hit position.
                if (m_Reticle)
                {
                    m_Reticle.SetPosition(hit);
                }
            }
            else
            {
                m_Target = null;
                // Position the reticle at default distance.
                if (m_Reticle)
                {
                    m_Reticle.SetPosition(ray.origin, ray.direction);
                }
            }
        }
示例#8
0
        /// <summary>
        /// Update the controller data from the provided platform state
        /// </summary>
        /// <param name="interactionSourceState">The InteractionSourceState retrieved from the platform</param>
        public void UpdateController(OVRInput.Controller ovrController, Transform trackingRoot)
        {
            if (!Enabled || trackingRoot == null)
            {
                return;
            }

            IsPositionAvailable = OVRInput.GetControllerPositionValid(ovrController);
            IsRotationAvailable = OVRInput.GetControllerOrientationValid(ovrController);

            // Update transform
            Vector3 localPosition = OVRInput.GetLocalControllerPosition(ovrController);
            Vector3 worldPosition = trackingRoot.TransformPoint(localPosition);
            // Debug.Log("Controller " + Handedness + " - local: " + localPosition + " - world: " + worldPosition);

            Quaternion localRotation = OVRInput.GetLocalControllerRotation(ovrController);
            Quaternion worldRotation = trackingRoot.rotation * localRotation;

            // Update velocity
            Vector3 localVelocity = OVRInput.GetLocalControllerVelocity(ovrController);

            Velocity = trackingRoot.TransformDirection(localVelocity);

            Vector3 localAngularVelocity = OVRInput.GetLocalControllerAngularVelocity(ovrController);

            AngularVelocity = trackingRoot.TransformDirection(localAngularVelocity);

            UpdateJointPoses();

            // If not rendering avatar hands, pointer pose is not available, so we approximate it
            if (IsPositionAvailable)
            {
                currentPointerPose.Position = currentGripPose.Position = worldPosition;
            }

            if (IsRotationAvailable)
            {
                currentPointerPose.Rotation = currentGripPose.Rotation = worldRotation;
            }

            // Todo: Complete touch controller mapping

            bool isTriggerPressed = false;
            bool isGripPressed    = false;

            if (ControllerHandedness == Handedness.Left)
            {
                isTriggerPressed = OVRInput.Get(OVRInput.RawAxis1D.LIndexTrigger) > cTriggerDeadZone;
                isGripPressed    = OVRInput.Get(OVRInput.RawAxis1D.LHandTrigger) > cTriggerDeadZone;
            }
            else
            {
                isTriggerPressed = OVRInput.Get(OVRInput.RawAxis1D.RIndexTrigger) > cTriggerDeadZone;
                isGripPressed    = OVRInput.Get(OVRInput.RawAxis1D.RHandTrigger) > cTriggerDeadZone;
            }

            for (int i = 0; i < Interactions?.Length; i++)
            {
                switch (Interactions[i].InputType)
                {
                case DeviceInputType.SpatialPointer:
                    Interactions[i].PoseData = currentPointerPose;
                    if (Interactions[i].Changed)
                    {
                        CoreServices.InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentPointerPose);
                    }
                    break;

                case DeviceInputType.SpatialGrip:
                    Interactions[i].PoseData = currentGripPose;
                    if (Interactions[i].Changed)
                    {
                        CoreServices.InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentGripPose);
                    }
                    break;

                case DeviceInputType.Select:
                    Interactions[i].BoolData = isTriggerPressed || isGripPressed;

                    if (Interactions[i].Changed)
                    {
                        if (Interactions[i].BoolData)
                        {
                            CoreServices.InputSystem?.RaiseOnInputDown(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                        else
                        {
                            CoreServices.InputSystem?.RaiseOnInputUp(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                    }
                    break;

                case DeviceInputType.TriggerPress:
                    Interactions[i].BoolData = isGripPressed || isTriggerPressed;

                    if (Interactions[i].Changed)
                    {
                        if (Interactions[i].BoolData)
                        {
                            CoreServices.InputSystem?.RaiseOnInputDown(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                        else
                        {
                            CoreServices.InputSystem?.RaiseOnInputUp(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                    }
                    break;

                case DeviceInputType.IndexFinger:
                    UpdateIndexFingerData(Interactions[i]);
                    break;
                }
            }
        }
示例#9
0
    // Update is called once per frame
    void Update()
    {
        bool trigger = OVRInput.Get(OVRInput.Button.SecondaryHandTrigger);
        shot s       = (shot)GameObject.Find("hand_right").GetComponent(typeof(shot));

        if (s.mode == 0)
        {
            if (trigger)
            {
                Vector3 contRot = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch).eulerAngles;

                Debug.Log(transform.position.x);
                if (contRot.x < 300.0f && contRot.x > 240.0f)
                {
                    if (transform.position.y < 25.0f)
                    {
                        transform.position += Vector3.up * 0.1f;
                    }
                }
                else if (contRot.x > 20.0f && contRot.x < 80.0f)
                {
                    if (transform.position.y > 7.0f)
                    {
                        transform.position += Vector3.down * 0.1f;
                    }
                }
                else if (contRot.z < 320.0f && contRot.z > 260.0f)
                {
                    if (transform.position.x < 6.0f)
                    {
                        transform.position += Vector3.right * 0.1f;
                    }
                }
                else if (contRot.z > 40.0f && contRot.z < 100.0f)
                {
                    if (transform.position.x > -2.0f)
                    {
                        transform.position += Vector3.left * 0.1f;
                    }
                }
            }
        }
        else
        {
            if (s.objToDrag && trigger)
            {
                Vector3 contRot = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch).eulerAngles;
                Debug.Log(s.objToDrag.transform.position);

                if (contRot.x < 300.0f && contRot.x > 240.0f)
                {
                    if (lastDir != 1 && s.objToDrag.transform.position.y < 3.0f)
                    {
                        s.objToDrag.transform.position += Vector3.up;
                    }
                    lastDir = 1;
                }
                else if (contRot.x > 20.0f && contRot.x < 80.0f)
                {
                    if (lastDir != 2 && s.objToDrag.transform.position.y > 0.0f)
                    {
                        s.objToDrag.transform.position += Vector3.down;
                    }
                    lastDir = 2;
                }
                else if (contRot.z > 40.0f && contRot.z < 100.0f)
                {
                    if (lastDir != 3 && s.objToDrag.transform.position.z > 0.0f)
                    {
                        s.objToDrag.transform.position += Vector3.back;
                    }
                    lastDir = 3;
                }
                else if (contRot.z < 320.0f && contRot.z > 260.0f)
                {
                    if (lastDir != 4 && s.objToDrag.transform.position.z < 3.0f)
                    {
                        s.objToDrag.transform.position += Vector3.forward;
                    }
                    lastDir = 4;
                }
                else
                {
                    lastDir = 0;
                }
            }
        }
    }
示例#10
0
    protected void GrabEnd()
    {
        if (m_grabbedObj != null)
        {
            OVRPose localPose = new OVRPose {
                position = OVRInput.GetLocalControllerPosition(m_controller), orientation = OVRInput.GetLocalControllerRotation(m_controller)
            };
            OVRPose offsetPose = new OVRPose {
                position = m_anchorOffsetPosition, orientation = m_anchorOffsetRotation
            };
            localPose = localPose * offsetPose;

            OVRPose trackingSpace = transform.ToOVRPose() * localPose.Inverse();
            OVRPose localVelocity = new OVRPose()
            {
                position = OVRInput.GetLocalControllerVelocity(m_controller), orientation = OVRInput.GetLocalControllerAngularVelocity(m_controller)
            };
            Vector3 linearVelocity  = trackingSpace.orientation * localVelocity.position;
            Vector3 angularVelocity = (trackingSpace.orientation * localVelocity.orientation).eulerAngles * Mathf.Deg2Rad;

            if (angularVelocity.x > Mathf.PI)
            {
                angularVelocity.x -= 2f * Mathf.PI;
            }
            if (angularVelocity.y > Mathf.PI)
            {
                angularVelocity.y -= 2f * Mathf.PI;
            }
            if (angularVelocity.z > Mathf.PI)
            {
                angularVelocity.z -= 2f * Mathf.PI;
            }

            GrabbableRelease(linearVelocity, angularVelocity);
        }

        // Re-enable grab volumes to allow overlap events
        GrabVolumeEnable(true);
    }
示例#11
0
    void CheckGrab(OVRInput.Controller hand, OVRInput.RawButton button)
    {
        if (OVRInput.GetDown(button))
        {
            Vector3 touchPos   = OVRManager.instance.transform.LocalToWorld(OVRInput.GetLocalControllerPosition(hand));
            Vector3 grabOffset = touchPos - transform.position;
            if (grabOffset.sqrMagnitude < grabRadius * grabRadius)
            {
                Quaternion invTouchRot = Quaternion.Inverse(OVRManager.instance.transform.LocalToWorld(OVRInput.GetLocalControllerRotation(hand)));

                grabbedBy         = hand;
                grabbedByButton   = button;
                localGrabOffset   = invTouchRot * (transform.position - touchPos);
                localGrabRotation = invTouchRot * transform.rotation;
                smoothedGrabVelocity.Clear();
            }
        }
    }
示例#12
0
        protected override void Update()
        {
            // A/X Button
            if (OVRInput.Get(OVRInput.Button.One, ovrController))
            {
                components[ButtonId.BUTTON1].press = true;
            }
            // B/Y Button
            if (OVRInput.Get(OVRInput.Button.Two, ovrController))
            {
                components[ButtonId.BUTTON2].press = true;
            }
            // Trigger
            if (OVRInput.Get(OVRInput.Touch.PrimaryIndexTrigger, ovrController))
            {
                components[ButtonId.TRIGGER].axis1 = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, ovrController);
                components[ButtonId.TRIGGER].touch = true;
            }
            if (OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger, ovrController))
            {
                components[ButtonId.TRIGGER].axis1 = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, ovrController);
                components[ButtonId.TRIGGER].press = true;
            }
            // Grip Trigger
            if (OVRInput.Get(OVRInput.Button.PrimaryHandTrigger, ovrController))
            {
                components[ButtonId.GRIP].axis1 = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, ovrController);
                components[ButtonId.GRIP].press = true;
            }
            // Thumb Stick
            if (OVRInput.Get(OVRInput.Touch.PrimaryThumbstick, ovrController))
            {
                components[ButtonId.THUMBPAD].axis1 = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, ovrController).x;
                components[ButtonId.THUMBPAD].axis2 = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, ovrController).y;
                components[ButtonId.THUMBPAD].touch = true;
            }
            if (OVRInput.Get(OVRInput.Button.PrimaryThumbstick, ovrController))
            {
                components[ButtonId.THUMBPAD].axis1 = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, ovrController).x;
                components[ButtonId.THUMBPAD].axis2 = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, ovrController).y;
                components[ButtonId.THUMBPAD].press = true;
            }
            // Thumb Rest
            if (OVRInput.Get(OVRInput.Touch.PrimaryThumbRest, ovrController))
            {
                components[ButtonId.THUMBREST].touch = true;
            }

            velocity = OVRInput.GetLocalControllerVelocity(ovrController);
            //angularVelocity = OVRInput.GetLocalControllerAngularVelocity(ovrController).eulerAngles;
            position = OVRInput.GetLocalControllerPosition(ovrController);
            rotation = OVRInput.GetLocalControllerRotation(ovrController);

            foreach (ControllerComponent c in components.Values)
            {
                c.UpdateComponent();
            }

            float elapsed = Time.time - hapticStartTime;

            if (elapsed >= hapticDuration)
            {
                OVRInput.SetControllerVibration(0f, 0f, ovrController);
            }
        }
    void Update()
    {
        if (leftController == null || rightController == null)
        {
            CopyMeshController();
        }
        else
        {
            padsAreInit = true;
        }

        if (padsAreInit)
        {
            RegisterPosition((int)CONTROLLER.LEFT, OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch));
            RegisterPosition((int)CONTROLLER.RIGHT, OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch));

            Pose p;
            p = GetValuePosition((int)CONTROLLER.LEFT, (float)(delay / 1000.0f));
            controllers[(int)CONTROLLER.LEFT].controller.transform.position = p.pose;
            controllers[(int)CONTROLLER.LEFT].controller.transform.rotation = p.rot;

            p = GetValuePosition((int)CONTROLLER.RIGHT, (float)(delay / 1000.0f));
            controllers[(int)CONTROLLER.RIGHT].controller.transform.position = p.pose;
            controllers[(int)CONTROLLER.RIGHT].controller.transform.rotation = p.rot;
        }

        if (controllerIndexZEDHolder != -1)
        {
            if (controllers[(int)controllerIndexZEDHolder].controller != null)
            {
                transform.parent.localPosition = controllers[(int)controllerIndexZEDHolder].controller.transform.position;
                transform.parent.localRotation = controllers[(int)controllerIndexZEDHolder].controller.transform.rotation;
            }
        }

        OVRInput.Update();
    }
示例#14
0
    // Update is called once per frame
    void Update()
    {
        if (OVRInput.GetDown(OVRInput.Button.Start))
        {
            Application.Quit();
        }

        if (OVRInput.GetDown(OVRInput.RawButton.A) && XYZW == true)
        {
            XYZW = false;
            Zrend.material.color = Color.red;
            YZXW = true;
            Xrend.material.color = Color.green;
        }
        else if (OVRInput.GetDown(OVRInput.RawButton.A) && YZXW == true)
        {
            YZXW = false;
            Xrend.material.color = Color.red;;
            XZYW = true;
            Yrend.material.color = Color.green;
        }
        else if (OVRInput.GetDown(OVRInput.RawButton.A) && XZYW == true)
        {
            XZYW = false;
            Yrend.material.color = Color.red;
            XYZW = true;
            Zrend.material.color = Color.green;
        }

        rotR = OVRInput.GetLocalControllerRotation(RightHand);
        rotL = OVRInput.GetLocalControllerRotation(LeftHand);

        if (OVRInput.GetDown(OVRInput.RawButton.RHandTrigger) || OVRInput.GetDown(OVRInput.RawButton.LHandTrigger))
        {
            DownR = OVRInput.GetLocalControllerRotation(RightHand);
            DownL = OVRInput.GetLocalControllerRotation(LeftHand);
            T     = rend.material.GetMatrix("_fdtransform");
        }

        if (OVRInput.GetUp(OVRInput.RawButton.RHandTrigger) || OVRInput.GetUp(OVRInput.RawButton.LHandTrigger))
        {
            DownR = OVRInput.GetLocalControllerRotation(RightHand);
            DownL = OVRInput.GetLocalControllerRotation(LeftHand);
            T     = rend.material.GetMatrix("_fdtransform");
            A     = Matrix4x4.identity;
            B     = Matrix4x4.identity;
        }

        Quaternion R = Quaternion.Inverse(DownR) * rotR;
        Quaternion L = Quaternion.Inverse(DownL) * rotL;

        eulerL = L.eulerAngles * (Mathf.PI / 180);
        eulerR = R.eulerAngles * (Mathf.PI / 180);

        if (XYZW)
        {
            if (OVRInput.Get(OVRInput.RawButton.RHandTrigger))
            {
                A = new Matrix4x4(
                    new Vector4(Mathf.Cos(eulerR.z), (-1) * Mathf.Sin(eulerR.z), 0f, 0f),
                    new Vector4(Mathf.Sin(eulerR.z), Mathf.Cos(eulerR.z), 0f, 0f),
                    new Vector4(0f, 0f, 1, 0),
                    new Vector4(0f, 0f, 0, 1));
            }
            if (OVRInput.Get(OVRInput.RawButton.LHandTrigger) && XYZW == true)
            {
                B = new Matrix4x4(
                    new Vector4(1, 0, 0f, 0f),
                    new Vector4(0, 1, 0f, 0f),
                    new Vector4(0f, 0f, Mathf.Cos(eulerL.z), (-1) * Mathf.Sin(eulerL.z)),
                    new Vector4(0f, 0f, Mathf.Sin(eulerL.z), Mathf.Cos(eulerL.z)));
            }
            rend.material.SetMatrix("_fdtransform", A * B * T);
        }

        if (YZXW)
        {
            if (OVRInput.Get(OVRInput.RawButton.RHandTrigger))
            {
                A = new Matrix4x4(
                    new Vector4(1, 0, 0, 0),
                    new Vector4(0, Mathf.Cos(eulerR.z), Mathf.Sin(eulerR.z), 0),
                    new Vector4(0, (-1) * Mathf.Sin(eulerR.z), Mathf.Cos(eulerR.z), 0),
                    new Vector4(0, 0, 0, 1));
            }
            if (OVRInput.Get(OVRInput.RawButton.LHandTrigger))
            {
                B = new Matrix4x4(
                    new Vector4(Mathf.Cos(eulerL.z), 0, 0, Mathf.Sin(eulerL.z)),
                    new Vector4(0, 1, 0, 0),
                    new Vector4(0, 0, 1, 0),
                    new Vector4((-1) * Mathf.Sin(eulerL.z), 0, 0, Mathf.Cos(eulerL.z)));
            }
            rend.material.SetMatrix("_fdtransform", A * B * T);
        }

        if (XZYW)
        {
            if (OVRInput.Get(OVRInput.RawButton.RHandTrigger))
            {
                A = new Matrix4x4(
                    new Vector4(Mathf.Cos(eulerR.z), 0, (-1) * Mathf.Sin(eulerR.z), 0),
                    new Vector4(0, 1, 0, 0),
                    new Vector4(Mathf.Sin(eulerR.z), 0, Mathf.Cos(eulerR.z), 0),
                    new Vector4(0, 0, 0, 1));
            }
            if (OVRInput.Get(OVRInput.RawButton.LHandTrigger))
            {
                B = new Matrix4x4(
                    new Vector4(1, 0, 0, 0),
                    new Vector4(0, Mathf.Cos(eulerL.z), 0, (-1) * Mathf.Sin(eulerL.z)),
                    new Vector4(0, 0, 1, 0),
                    new Vector4(0, Mathf.Sin(eulerL.z), 0, Mathf.Cos(eulerL.z)));
            }
            rend.material.SetMatrix("_fdtransform", A * B * T);
        }

        if (OVRInput.GetDown(OVRInput.RawButton.B))
        {
            A = Matrix4x4.identity;
            B = Matrix4x4.identity;
            T = Matrix4x4.identity;
        }
    }
    private void Update()
    {
        //check out if this changees to a specific amount, then adjust it for that, remove that
        transform.localPosition = OVRInput.GetLocalControllerPosition(controller);;
        transform.localRotation = OVRInput.GetLocalControllerRotation(controller);
        joy = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, controller);
        isTriggerPressed = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller);

        // Cursor
        if (Physics.Raycast(transform.position, transform.forward, out hit, 15.0f) && hit.collider.gameObject.tag != "Marker")
        {
            marker.transform.position = hit.point;

            if (hit.collider.gameObject.tag == "LeftHand" || hit.collider.gameObject.tag == "Button")
            {
                marker.transform.localScale = new Vector3(0.02f, 0.02f, 0.02f);
            }
            else
            {
                marker.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
            }
        }
        else
        {
            marker.transform.position = new Vector3(0, -5, 0);
        }

        //Press Button Once
        if (buttonLock && isTriggerPressed == 0)
        {
            buttonLock = false;
        }

        // Button
        if (hit.collider != null)
        {
            if (isTriggerPressed > 0 && !buttonLock)
            {
                if (hit.collider.gameObject.tag == "Button" || hit.collider.gameObject.tag == "BigButton")
                {
                    Button button = hit.collider.gameObject.GetComponent <Button>();
                    if (button != null)
                    {
                        button.onClick();
                        buttonLock = true;
                    }
                }
            }
        }

        /*if (hit.collider.gameObject.name == "Button") {
         *      hit.collider.gameObject.GetComponent<Button> ().cursorEnter ();
         *      currentSelectedButton = hit.collider.gameObject;
         * } else if (hit.collider.gameObject.tag == "Exterior Walls") {
         *      hit.collider.gameObject.GetComponent<ExteriorWalls> ().changeVisibility ();
         * } else if (hit.collider.gameObject.name == "RemoveWallsButton") {
         *      hit.collider.GetComponent<TestButton> ().cursorEnter ();
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              c.startTime ();
         *              wallsActive = !wallsActive;
         *              foreach (ExteriorWalls g in (GameObject.FindObjectsOfType<ExteriorWalls>()))
         *                      if (wallsActive)
         *                              g.changeVisibility ();
         *                      else
         *                              g.changeVisibility ();
         *      }
         * } else if (hit.collider.gameObject.name == "SeasonGUIButton") {
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              c.startTime ();
         *              hit.collider.GetComponent<SeasonGUIButton> ().seasonChange ();
         *              GameObject.FindObjectOfType<SunControl> ().ChangeSun (GameObject.FindObjectOfType<SeasonGUIButton> ().getSeason () * 3 + GameObject.FindObjectOfType<TimeGUIButton> ().getTime ());
         *      }
         * } else if (hit.collider.gameObject.name == "TimeGUIButton") {
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              c.startTime ();
         *              hit.collider.GetComponent<TimeGUIButton> ().timeChange ();
         *              GameObject.FindObjectOfType<SunControl> ().ChangeSun (GameObject.FindObjectOfType<SeasonGUIButton> ().getSeason () * 3 + GameObject.FindObjectOfType<TimeGUIButton> ().getTime ());
         *
         *      }
         * } else if (hit.collider.gameObject.name == "HomeButton") {
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              camera.transform.position = new Vector3 (-39f, 35f, 46f);
         *      }
         * }else if (hit.collider.gameObject.name == "BuildingButton") {
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              camera.transform.position = new Vector3 (331f, 35f, 410f);
         *              GameObject.Find ("E2 Revised Animation").GetComponent<Animation> ().Rewind ();
         *              GameObject.Find ("E2_BuildingAnimation_050917").GetComponent<Animation> ().Rewind ();
         *              GameObject.Find ("E2 Revised Animation").GetComponent<Animation> ().Play ();
         *              GameObject.Find ("E2_BuildingAnimation_050917").GetComponent<Animation> ().Play ();
         *      }
         *
         * }else if (hit.collider.gameObject.name == "SoilProfileButton") {
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              camera.transform.position = new Vector3 (631f, 60f, 359f);
         *              GameObject.Find ("Soil Animation - 120516").GetComponent<Animation> ().Rewind ();
         *              GameObject.Find ("Soil Animation - 120516").GetComponent<Animation> ().Play ();
         *      }
         *
         * }else if (hit.collider.gameObject.name == "SIPAPanelsButton") {
         *      if (OVRInput.Get (OVRInput.Button.One) && c.ready ()) {
         *              camera.transform.position = new Vector3 (47.16f, 35f, 357f);
         *              GameObject.Find ("E2 Animation Khandakar").GetComponent<Animation> ().Rewind ();
         *              GameObject.Find ("E2 Animation Khandakar").GetComponent<Animation> ().Play ();
         *      }
         *
         * }else {
         *      foreach (TestButton tb in GameObject.FindObjectsOfType<TestButton>())
         *              tb.cursorExit ();
         * }
         * }*/


        // Teleportation
        if (OVRInput.Get(OVRInput.Button.One, controller) && !teleportStarted)
        {
            //print ("asd");
            //Debug.Log("A Pressed");
            if (hit.collider != null)
            {
                if (hit.collider.gameObject.tag == "Walkable")
                {
                    teleportStarted = true;
                    StartCoroutine(Teleport());
                }
            }
        }

        //Camera Rotation
        camera.transform.Rotate(new Vector3(0, joy.x, 0));
    }
示例#16
0
    public Vector3 calcCursorOrientation()
    {
        //get{
        //if (_originCursorPosition != new Vector3()) {
        //	return ((1.0f - CursorOrientationFactor) * (_originCursorRotation * Vector3.up) + CursorOrientationFactor * (_originCursorRotation * Vector3.right)).normalized;
        //}
        //else{

        /***
         * experiment to see if we can predict what orientation the user wants the stroke in without lookahead like tilt brush
         * if (_currPoint != new Vector3 ()) {
         *      Vector3 curr = _currPoint - OVRInput.GetLocalControllerPosition (_dominantHand);
         *      Vector3 prev = _prevPoint - OVRInput.GetLocalControllerPosition (_dominantHand);
         *      Vector3 orientation = Vector3.Cross (curr, prev).normalized;
         *
         *      return orientation;
         * } else {
         *      return ((1.0f - CursorOrientationFactor) * (OVRInput.GetLocalControllerRotation (_dominantHand) * Vector3.up) + CursorOrientationFactor * (OVRInput.GetLocalControllerRotation (_dominantHand) * Vector3.right)).normalized;
         * }
         ***/

        return(((1.0f - CursorOrientationFactor) * (OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.up) + CursorOrientationFactor * (OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.right)).normalized);
        //}
        //}
    }
示例#17
0
    private void EyeRaycast()
    {
        Debug.Log("eye1");
        // Show the debug ray if required
        if (m_ShowDebugRay)
        {
            Debug.DrawRay(m_Camera.position, m_Camera.forward * m_DebugRayLength, Color.blue, m_DebugRayDuration);
        }

        // Create a ray that points forwards from the camera.
        Ray        ray = new Ray(m_Camera.position, m_Camera.forward);
        RaycastHit hit;

        Vector3 worldStartPoint = Vector3.zero;
        Vector3 worldEndPoint   = Vector3.zero;

        if (m_LineRenderer != null)
        {
            m_LineRenderer.enabled = ControllerIsConnected && ShowLineRenderer;
        }
        Debug.Log("eye2");

        if (ControllerIsConnected && m_TrackingSpace != null)
        {
            Matrix4x4  localToWorld = m_TrackingSpace.localToWorldMatrix;
            Quaternion orientation  = OVRInput.GetLocalControllerRotation(Controller);

            Vector3 localStartPoint = OVRInput.GetLocalControllerPosition(Controller);
            Vector3 localEndPoint   = localStartPoint + ((orientation * Vector3.forward) * 500.0f);

            worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
            worldEndPoint   = localToWorld.MultiplyPoint(localEndPoint);
            Debug.Log("Update worldEndPoint");

            // Create new ray
            ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
        }
        Debug.Log("eye3");

        // Update selected object
        if (m_SelectedInteractible && m_SelectedInteractible.menuItem == false)
        {
            m_SelectedInteractible.gameObject.transform.position = worldStartPoint + ray.direction;
            m_SelectedInteractible.gameObject.transform.rotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTrackedRemote);
        }

        // Put selected object back
        if (OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger) && m_SelectedInteractible && m_SelectedInteractible.menuItem == false)
        {
            m_SelectedInteractible.transform.position = m_SelectedInteractibleOriginalPosition;
            m_SelectedInteractible = null;
        }
        Debug.Log("eye4");

        // Do the raycast forweards to see if we hit an interactive item
        if (Physics.Raycast(ray, out hit, m_RayLength, ~m_ExclusionLayers))
        {
            VRInteractiveItem interactible = hit.collider.GetComponent <VRInteractiveItem>(); //attempt to get the VRInteractiveItem on the hit object
            if (interactible)
            {
                if (m_SelectedInteractible == null && OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger))
                {
                    m_SelectedInteractible = interactible;
                    m_SelectedInteractibleOriginalPosition = m_SelectedInteractible.gameObject.transform.position;
                    Material material = new Material(Shader.Find("Diffuse"));
                    material.mainTexture = m_SelectedInteractible.TheoryTexture;
                    m_SelectedInteractible.TheoryScreen.GetComponent <Renderer>().material = material;
                }
                worldEndPoint = hit.point;
                Debug.Log("Update worldEndPoint hit");
            }
            m_CurrentInteractible = interactible;
            Debug.Log("eye5");


            // If we hit an interactive item and it's not the same as the last interactive item, then call Over
            if (interactible && interactible != m_LastInteractible)
            {
                interactible.Over();
            }

            // Deactive the last interactive item
            if (interactible != m_LastInteractible)
            {
                DeactiveLastInteractible();
            }

            m_LastInteractible = interactible;

            // Something was hit, set at the hit position.
            if (m_Reticle)
            {
                m_Reticle.SetPosition(hit);
            }
            Debug.Log("eye6");

            if (OnRaycasthit != null)
            {
                OnRaycasthit(hit);
            }
        }
        else
        {
            // Nothing was hit, deactive the last interactive item.
            DeactiveLastInteractible();
            m_CurrentInteractible = null;

            // Position the reticle at default distance.
            if (m_Reticle)
            {
                m_Reticle.SetPosition(ray.origin, ray.direction);
            }
        }
        if (ControllerIsConnected && m_LineRenderer != null)
        {
            Debug.Log("eye" + worldEndPoint.x + " " + worldEndPoint.y + " " + worldEndPoint.z);
            m_LineRenderer.SetPosition(0, worldStartPoint);
            m_LineRenderer.SetPosition(1, worldEndPoint);
        }
        Debug.Log("eye7");
    }
示例#18
0
    // Update is called once per frame
    void Update()
    {
        findPlaneClosestTo3DCursor();
        // the interaction cursor is positioned where the cursor is
        //interactionCursor.transform.position = calcInteractionCursorPosition ();

        // debugging purposes
        if (debugMode)
        {
            DrawDebug();
        }

        DrawCursor(StripWidth);
        // change the orientation of the strip on the basis of the joystick press right
        if (OVRInput.Get(OVRInput.Button.PrimaryThumbstickRight, _dominantHand))
        {
            CursorOrientationFactor += 0.02f;
            //StrokeOrientation = Vector3.RotateTowards (StrokeOrientation, OVRInput.GetLocalControllerRotation (OVRInput.Controller.RTouch) * Vector3.right, 0.05f, 0.0f);
        }
        else if (OVRInput.Get(OVRInput.Button.PrimaryThumbstickLeft, _dominantHand))
        {
            CursorOrientationFactor -= 0.02f;
            //StrokeOrientation = Vector3.RotateTowards (StrokeOrientation, OVRInput.GetLocalControllerRotation (OVRInput.Controller.RTouch) * Vector3.up, 0.05f, 0.0f);
        }

        /*
         * // change the transparency of the avatar if the controller button 'A' is pressed. This was done so that I could see the 3D strokes that I have made more clearly
         * if (OVRInput.Get (OVRInput.Button.Two, OVRInput.Controller.RTouch)) {
         *      _baseMeshRenderer.material.color = new Color(_baseMeshRenderer.material.color.r, _baseMeshRenderer.material.color.g, _baseMeshRenderer.material.color.b, 0.0f);
         *      //baseMesh.SetActive (false);
         * } else {
         *      //baseMesh.SetActive (true);
         *      _baseMeshRenderer.material.color = new Color(_baseMeshRenderer.material.color.r, _baseMeshRenderer.material.color.g, _baseMeshRenderer.material.color.b, 1.0f);
         * }
         */

        // Lets try giving the user a control on determining the distance of the 3D cursor from the controller. "A" button brings the cursor closer and "B" button pushes it away
        if (OVRInput.Get(OVRInput.Button.Two, _dominantHand))
        {
            _cursorDistance += _cursorDistanceSpeed;
        }
        if (OVRInput.Get(OVRInput.Button.One, _dominantHand))
        {
            _cursorDistance -= _cursorDistanceSpeed;
        }

        // Change the width of the strip on the basis of the joystick press down
        if (OVRInput.Get(OVRInput.Button.PrimaryThumbstickUp, _dominantHand))
        {
            StripWidth += stripWidthChangeFactor;
        }
        else if (OVRInput.Get(OVRInput.Button.PrimaryThumbstickDown, _dominantHand))
        {
            StripWidth -= stripWidthChangeFactor;
        }

        // Start and stop the strip drawing process
        // create the strip gameobject and setup initial parameters
        if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger, _dominantHand))
        {
            GameObject go = createStrokeGameObject();
            _currLine = go.AddComponent <MeshLineRenderer> ();
            _currLine.SetMaterial(new Material(strokeMat));
            _currLine.setWidth(StripWidth);
            _currLine.SetOrientation(calcCursorOrientation());
            //currLine.endWidth = 0.1f;
            numClicks     = 0;
            _prevPoint    = calcCursorPosition();
            ModeDetermine = "drawing";
        }
        // add strips to the existing stroke that you are drawing
        else if (OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger, _dominantHand))
        {
            //currLine.positionCount = numClicks + 1;
            //currLine.SetPosition (numClicks, OVRInput.GetLocalControllerPosition (OVRInput.Controller.RTouch));
            _currLine.setWidth(StripWidth);
            _currPoint = calcCursorPosition();
            cleanPoint(_currLine, _currPoint);
            _currLine.SetOrientation(calcCursorOrientation());
            _prevPoint = _currPoint;
            numClicks++;
        }
        // when you stop drawing change the mode to idle so that you can respond to ui changes again
        else if (OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger, _dominantHand))
        {
            ModeDetermine = "idle";
        }


        /*
         * if (CollisionDetector.CollidingBodyPart != null) {
         *      Debug.Log (CollisionDetector.CollidingBodyPart.transform.name);
         * }*/

        // event system for detecting the frame where gripDown happens
        if (OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, _dominantHand) > 0.9f)
        {
            if (_gripDownCount == 0)
            {
                _gripDownCount = 1;
                _gripDown      = true;
            }
            else
            {
                _gripDown = false;
            }
        }
        else
        {
            if (_gripDownCount == 1)
            {
                _gripDownCount = 0;
            }
        }

        // assigning the origin of the drawing surface as this origin's x,y has to be defined in order to use the magnified surface.
        if (_gripDown)
        {
            if (_originCursorPosition == new Vector3())
            {
                _originCursorPosition = calcCursorPosition();
                _originCursorRotation = OVRInput.GetLocalControllerRotation(_dominantHand);
                Vector3 scale = new Vector3(0.02f, 0.02f, 0.02f);
                GenerateGrid(_originCursorPosition, _originCursorRotation, scale);
            }
            else
            {
                _originCursorPosition = new Vector3();
                _originCursorRotation = new Quaternion();
                _grid.SetActive(false);
            }
        }
    }
    void Update()
    {
        OVRInput.Controller activeController = OVRInput.GetActiveController();

        data.Length = 0;
        byte recenterCount = OVRInput.GetControllerRecenterCount();

        data.AppendFormat("RecenterCount: {0}\n", recenterCount);

        byte battery = OVRInput.GetControllerBatteryPercentRemaining();

        data.AppendFormat("Battery: {0}\n", battery);

        float framerate = OVRPlugin.GetAppFramerate();

        data.AppendFormat("Framerate: {0:F2}\n", framerate);

        string activeControllerName = activeController.ToString();

        data.AppendFormat("Active: {0}\n", activeControllerName);

        string connectedControllerNames = OVRInput.GetConnectedControllers().ToString();

        data.AppendFormat("Connected: {0}\n", connectedControllerNames);

        data.AppendFormat("PrevConnected: {0}\n", prevConnected);

        controllers.Update();
        controllers.AppendToStringBuilder(ref data);

        prevConnected = connectedControllerNames;

        Quaternion rot = OVRInput.GetLocalControllerRotation(activeController);

        data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", rot.x, rot.y, rot.z, rot.w);

        Vector3 angVel = OVRInput.GetLocalControllerAngularVelocity(activeController);

        data.AppendFormat("AngVel: ({0:F2}, {1:F2}, {2:F2})\n", angVel.x, angVel.y, angVel.z);

        Vector3 angAcc = OVRInput.GetLocalControllerAngularAcceleration(activeController);

        data.AppendFormat("AngAcc: ({0:F2}, {1:F2}, {2:F2})\n", angAcc.x, angAcc.y, angAcc.z);

        Vector3 pos = OVRInput.GetLocalControllerPosition(activeController);

        data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", pos.x, pos.y, pos.z);

        Vector3 vel = OVRInput.GetLocalControllerVelocity(activeController);

        data.AppendFormat("Vel: ({0:F2}, {1:F2}, {2:F2})\n", vel.x, vel.y, vel.z);

        Vector3 acc = OVRInput.GetLocalControllerAcceleration(activeController);

        data.AppendFormat("Acc: ({0:F2}, {1:F2}, {2:F2})\n", acc.x, acc.y, acc.z);

        Vector2 primaryTouchpad = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad);

        data.AppendFormat("PrimaryTouchpad: ({0:F2}, {1:F2})\n", primaryTouchpad.x, primaryTouchpad.y);

        Vector2 secondaryTouchpad = OVRInput.Get(OVRInput.Axis2D.SecondaryTouchpad);

        data.AppendFormat("SecondaryTouchpad: ({0:F2}, {1:F2})\n", secondaryTouchpad.x, secondaryTouchpad.y);

        float indexTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);

        data.AppendFormat("PrimaryIndexTriggerAxis1D: ({0:F2})\n", indexTrigger);

        float handTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger);

        data.AppendFormat("PrimaryHandTriggerAxis1D: ({0:F2})\n", handTrigger);

        for (int i = 0; i < monitors.Count; i++)
        {
            monitors[i].Update();
            monitors[i].AppendToStringBuilder(ref data);
        }

        if (uiText != null)
        {
            uiText.text = data.ToString();
        }
    }
示例#20
0
    void findPlaneClosestTo3DCursor()
    {
        //testOne.DetectPlaneAtHit (Vector3);
        // the origin is moved beyond the interaction cursor position so as not to detect the raycast collision with it
        Vector3    origin = OVRInput.GetLocalControllerPosition(_dominantHand) + 0.3f * (OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.forward);
        Ray        ray    = new Ray(origin, OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.forward);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100.0f))
        {
            Debug.Log("hit detected" + hit.collider.transform.gameObject.name);
        }
        //Debug.Log (Camera.main.gameObject.name);
    }
        private void EyeRaycast()
        {
            // Show the debug ray if required
            if (m_ShowDebugRay)
            {
                Debug.DrawRay(m_Camera.position, m_Camera.forward * m_DebugRayLength, Color.blue, m_DebugRayDuration);
            }

            // Create a ray that points forwards from the camera.
            Ray        ray = new Ray(m_Camera.position, m_Camera.forward);
            RaycastHit hit;

            // Creates start and end point of the laser
            Vector3 worldStartPoint = Vector3.zero;
            Vector3 worldEndPoint   = Vector3.zero;

            // Check to see if a controller is present
            if (m_LineRenderer != null)
            {
                m_LineRenderer.enabled = ControllerIsConnected && ShowLineRenderer;
            }

            // If there is a controller connected, create a new ray
            if (ControllerIsConnected && m_trackingSpace != null)
            {
                Matrix4x4  localToWorld = m_trackingSpace.localToWorldMatrix;
                Quaternion orientation  = OVRInput.GetLocalControllerRotation(Controller);

                Vector3 localStartPoint = OVRInput.GetLocalControllerPosition(Controller);
                Vector3 localEndPoint   = localStartPoint + ((orientation * Vector3.forward) * 500.0f);

                worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
                worldEndPoint   = localToWorld.MultiplyPoint(localEndPoint);

                // Create new ray
                ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
            }

            // Do the raycast forweards to see if we hit an interactive item
            if (Physics.Raycast(ray, out hit, m_RayLength, ~m_ExclusionLayers))
            {
                VRInteractiveItem interactible = hit.collider.GetComponent <VRInteractiveItem>(); //attempt to get the VRInteractiveItem on the hit object
                m_CurrentInteractible = interactible;

                if (interactible)
                {
                    worldEndPoint = hit.point;
                }

                // If we hit an interactive item and it's not the same as the last interactive item, then call Over
                if (interactible && interactible != m_LastInteractible)
                {
                    interactible.Over();
                }

                // Deactive the last interactive item
                if (interactible != m_LastInteractible)
                {
                    DeactiveLastInteractible();
                }

                m_LastInteractible = interactible;

                // Something was hit, set at the hit position.
                if (m_Reticle)
                {
                    m_Reticle.SetPosition(hit);
                }

                if (OnRaycasthit != null)
                {
                    OnRaycasthit(hit);
                }
            }
            else
            {
                // Nothing was hit, deactive the last interactive item.
                DeactiveLastInteractible();
                m_CurrentInteractible = null;

                // Position the reticle at default distance.
                if (m_Reticle)
                {
                    m_Reticle.SetPosition(ray.origin, ray.direction);
                }
            }

            if (ControllerIsConnected && m_LineRenderer != null)
            {
                m_LineRenderer.SetPosition(0, worldStartPoint);
                m_LineRenderer.SetPosition(1, worldEndPoint);
            }
        }
示例#22
0
 void DrawDebug()
 {
     _debugRenderer.SetPosition(0, OVRInput.GetLocalControllerPosition(_dominantHand));
     _debugRenderer.SetPosition(1, OVRInput.GetLocalControllerPosition(_dominantHand) + 10.0f * (OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.forward));
 }
    /// <summary>
    /// Update is called every frame.
    /// For SteamVR plugin this is where the device Index is set up.
    /// For Oculus plugin this is where the tracking is done.
    /// </summary>
    protected virtual void Update()
    {
#if ZED_OCULUS //Used only if the Oculus Integration plugin is detected.
        //Check if the VR headset is connected.
        if (OVRManager.isHmdPresent && loadeddevice == "Oculus")
        {
            if (OVRInput.GetConnectedControllers().ToString().ToLower().Contains("touch"))
            {
                //Depending on which tracked device we are looking for, start tracking it.
                if (deviceToTrack == Devices.LeftController) //Track the Left Oculus Controller.
                {
                    RegisterPosition(1, OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch));
                }
                if (deviceToTrack == Devices.RightController) //Track the Right Oculus Controller.
                {
                    RegisterPosition(1, OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch));
                }

                if (deviceToTrack == Devices.Hmd) //Track the Oculus Hmd.
                {
                    RegisterPosition(1, InputTracking.GetLocalPosition(XRNode.CenterEye), InputTracking.GetLocalRotation(XRNode.CenterEye));
                }

                //Use our saved positions to apply a delay before assigning it to this object's Transform.
                if (poseData.Count > 0)
                {
                    sl.Pose p;

                    //Delay the saved values inside GetValuePosition() by a factor of latencyCompensation in milliseconds.
                    p = GetValuePosition(1, (float)(latencyCompensation / 1000.0f));
                    transform.position = p.translation; //Assign new delayed Position
                    transform.rotation = p.rotation;    //Assign new delayed Rotation.
                }
            }
        }
        //Enable updating the internal state of OVRInput.
        OVRInput.Update();
#endif
#if ZED_STEAM_VR
        UpdateControllerState();        //Get the button states so we can check if buttons are down or not.

        timerSteamVR += Time.deltaTime; //Increment timer for checking on devices

        if (timerSteamVR <= timerMaxSteamVR)
        {
            return;
        }

        timerSteamVR = 0f;

        //Checks if a device has been assigned
        if (index == EIndex.None && loadeddevice == "OpenVR")
        {
            //We look for any device that has "tracker" in its 3D model mesh name.
            //We're doing this since the device ID changes based on how many devices are connected to SteamVR.
            //This way, if there's no controllers or just one, it's going to get the right ID for the Tracker.
            if (deviceToTrack == Devices.ViveTracker)
            {
                var error = ETrackedPropertyError.TrackedProp_Success;
                for (uint i = 0; i < 16; i++)
                {
                    var result = new System.Text.StringBuilder((int)64);
                    OpenVR.System.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_RenderModelName_String, result, 64, ref error);
                    if (result.ToString().Contains("tracker"))
                    {
                        index = (EIndex)i;
                        break; //We break out of the loop, but we can use this to set up multiple Vive Trackers if we want to.
                    }
                }
            }

            //Looks for a device with the role of a Right Hand.
            if (deviceToTrack == Devices.RightController)
            {
                index = (EIndex)OpenVR.System.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.RightHand);
            }
            //Looks for a device with the role of a Left Hand.
            if (deviceToTrack == Devices.LeftController)
            {
                index = (EIndex)OpenVR.System.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.LeftHand);
            }

            //Assigns the HMD.
            if (deviceToTrack == Devices.Hmd)
            {
                index = EIndex.Hmd;
            }

            //Display a warning if there was supposed to be a calibration file, and none was found.
            if (SNHolder.Equals("NONE"))
            {
                UnityEngine.Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.PAD_CAMERA_CALIBRATION_NOT_FOUND));
            }
            else if (SNHolder != null && index != EIndex.None) //
            {
                //If the Serial number of the Calibrated device isn't the same as the current tracked device by this script...
                var snerror  = ETrackedPropertyError.TrackedProp_Success;
                var snresult = new System.Text.StringBuilder((int)64);
                OpenVR.System.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_SerialNumber_String, snresult, 64, ref snerror);
                if (!snresult.ToString().Contains(SNHolder))
                {
                    UnityEngine.Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.PAD_CAMERA_CALIBRATION_MISMATCH) + " Serial Number: " + SNHolder);
                    //... then look for that device through all the connected devices.
                    for (int i = 0; i < 16; i++)
                    {
                        //If a device with the same Serial Number is found, then change the device to track of this script.
                        var chsnresult = new System.Text.StringBuilder((int)64);
                        OpenVR.System.GetStringTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_SerialNumber_String, chsnresult, 64, ref snerror);
                        if (snresult.ToString().Contains(SNHolder))
                        {
                            index = (EIndex)i;
                            string deviceRole = OpenVR.System.GetControllerRoleForTrackedDeviceIndex((uint)index).ToString();
                            if (deviceRole.Equals("RightHand"))
                            {
                                deviceToTrack = Devices.RightController;
                            }
                            else if (deviceRole.Equals("LeftHand"))
                            {
                                deviceToTrack = Devices.LeftController;
                            }
                            else if (deviceRole.Equals("Invalid"))
                            {
                                var error  = ETrackedPropertyError.TrackedProp_Success;
                                var result = new System.Text.StringBuilder((int)64);
                                OpenVR.System.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, result, 64, ref error);
                                if (result.ToString().Contains("tracker"))
                                {
                                    deviceToTrack = Devices.ViveTracker;
                                }
                            }
                            UnityEngine.Debug.Log("A connected device with the correct Serial Number was found, and assigned to " + this + " the correct device to track.");
                            break;
                        }
                    }
                }
            }
            oldDevice = deviceToTrack;
        }

        if (deviceToTrack != oldDevice)
        {
            index = EIndex.None;
        }
#endif
    }
示例#24
0
    /**
     * // calculate the position of the interaction cursor, put it 0.1 m in front of the touch controller
     * private Vector3 calcInteractionCursorPosition(){
     *      Vector3 controllerPosition = OVRInput.GetLocalControllerPosition (_dominantHand);
     *      return controllerPosition + 0.1f * (OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.forward);
     * }
     */
    private Vector3 calcCursorPosition()
    {
        //return OVRInput.GetLocalControllerPosition (OVRInput.Controller.RTouch) + 0.1f * (OVRInput.GetLocalControllerRotation (OVRInput.Controller.RTouch) * Vector3.forward);
        Vector3 controllerPosition = OVRInput.GetLocalControllerPosition(_dominantHand);


        //return OVRInput.GetLocalControllerPosition (OVRInput.Controller.RTouch) + _cursorDistance * (OVRInput.GetLocalControllerRotation (OVRInput.Controller.RTouch) * Vector3.forward);

        if (_originCursorPosition != new Vector3())
        {
            Vector3 newX           = _originCursorRotation * Vector3.right;
            Vector3 newY           = _originCursorRotation * Vector3.up;
            Vector3 diff           = controllerPosition - _originCursorPosition;
            Vector3 scaledDiffNewX = (((_cursorDistance - 0.1f) * 20.0f) * Vector3.Dot(diff, newX)) * newX.normalized;
            Vector3 scaledDiffNewY = (((_cursorDistance - 0.1f) * 20.0f) * Vector3.Dot(diff, newY)) * newY.normalized;
            //Vector3 finalVector = ( * (diffNewX + diffNewY));
            //Vector3 newZ = OVRInput.GetLocalControllerPosition(_dominantHand) + _cursorDistance * (_originCursorRotation * Vector3.forward);
            Vector3 newZ = _originCursorPosition;
            return(scaledDiffNewX + scaledDiffNewY + newZ);
            //return new Vector3 (_originCursorPosition.x+((controllerPosition.x-_originCursorPosition.x) * ((_cursorDistance-0.1f)*20.0f)), _originCursorPosition.y+((controllerPosition.y-_originCursorPosition.y) * ((_cursorDistance-0.1f)*20.0f)), controllerPosition.z) + _cursorDistance * (Vector3.forward);
        }
        else
        {
            return(OVRInput.GetLocalControllerPosition(_dominantHand) + _cursorDistance * (OVRInput.GetLocalControllerRotation(_dominantHand) * Vector3.forward));
        }
    }
示例#25
0
 void Update()
 {
     transform.localPosition = OVRInput.GetLocalControllerPosition(Controller);
     transform.localRotation = OVRInput.GetLocalControllerRotation(Controller);
 }
示例#26
0
    // Update is called once per frame
    void Update()
    {
        transform.localPosition = OVRInput.GetLocalControllerPosition(controller);
        transform.localRotation = OVRInput.GetLocalControllerRotation(controller);

        if (controller == OVRInput.Controller.RTouch)
        {
            if (OVRInput.GetDown(OVRInput.Button.One, controller))
            {
            }

            if (OVRInput.GetDown(OVRInput.Button.Two, controller))
            {
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller) > 0)
            {
                //print(controller.ToString() + ": Trigger on");
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller) <= 0)
            {
                //print(controller.ToString() + ": Trigger off");
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, controller) > 0)
            {
                //print(controller.ToString() + ": Grip on");
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, controller) <= 0)
            {
                //print(controller.ToString() + ": Grip off");
            }
        }

        else if (controller == OVRInput.Controller.LTouch)
        {
            if (OVRInput.GetDown(OVRInput.Button.One, controller))
            {
            }

            if (OVRInput.GetDown(OVRInput.Button.Two, controller))
            {
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller) > 0)
            {
                //print(controller.ToString() + ": Trigger on");
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller) <= 0)
            {
                //print(controller.ToString() + ": Trigger off");
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, controller) > 0)
            {
                //print(controller.ToString() + ": Grip on");
            }

            if (OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, controller) <= 0)
            {
                //print(controller.ToString() + ": Grip off");
            }
        }
    }
示例#27
0
 public void releaseFunction(OVRInput.Controller hand)
 {
     releaseFunctionConcrete(OVRInput.GetLocalControllerPosition(hand), getWorldPosition(hand), OVRInput.GetLocalControllerRotation(hand), getWorldRotation(hand));
 }
示例#28
0
        private void EyeRaycast()
        {
            // Show the debug ray if required
            if (m_ShowDebugRay)
            {
                Debug.DrawRay(m_Camera.position, m_Camera.forward * m_DebugRayLength, Color.blue, m_DebugRayDuration);
            }

            // Create a ray that points forwards from the camera.
            Ray ray;

            Vector3 worldStartPoint;
            Vector3 worldEndPoint;

            switch (PlatformManager.Instance.currentVRPlatform)
            {
            case VRPlataform.PC:
            default:
                worldStartPoint = m_Camera.position;
                worldEndPoint   = worldStartPoint + (worldStartPoint * m_RayLength);
                ray             = new Ray(m_Camera.position, m_Camera.forward);
                break;

            case VRPlataform.Oculus:
                Matrix4x4  localToWorld = m_TrackingSpace.localToWorldMatrix;
                Quaternion orientation  = OVRInput.GetLocalControllerRotation(Controller);

                Vector3 localStartPoint = OVRInput.GetLocalControllerPosition(Controller);
                Vector3 localEndPoint   = localStartPoint + ((orientation * Vector3.forward) * m_RayLength);

                worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
                worldEndPoint   = localToWorld.MultiplyPoint(localEndPoint);

                // Create new ray
                ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
                break;
            }

            //first look for UI elements
            hits = Physics.RaycastAll(ray, m_RayLength, m_UILayers);

            #if UNITY_EDITOR
            if (Input.GetKeyDown(KeyCode.Space))
            {
                foreach (var item in hits)
                {
                    print(item.transform.name + "_" + item.distance);
                }
                print("_______________________");
            }
#endif

            // Do the raycast forwards to see if we hit an interactive item
            if (hits.Length > 0)
            {
                ProcessRaycastHits(hits, worldStartPoint, out worldEndPoint);

                RenderLine(worldStartPoint, worldEndPoint);

                return;
            }

            //if there is no hit, then look for other colliders
            hits = Physics.RaycastAll(ray, m_RayLength, ~m_ExclusionLayers);

#if UNITY_EDITOR
            if (Input.GetKeyDown(KeyCode.Space))
            {
                foreach (var item in hits)
                {
                    print(item.transform.name);
                }
                print("_______________________");
            }
#endif

            // Do the raycast forwards to see if we hit an interactive item
            if (hits.Length > 0)
            {
                ProcessRaycastHits(hits, worldStartPoint, out worldEndPoint);
            }
            else
            {
                // Nothing was hit, deactive the last interactive item.
                DeactiveLastInteractible();
                m_CurrentInteractible = null;
                // Position the reticle at default distance.
                if (m_Reticle)
                {
                    m_Reticle.SetPosition(ray.origin, ray.direction);
                }
            }

            RenderLine(worldStartPoint, worldEndPoint);
        }
示例#29
0
    protected void GrabEnd()
    {
        this.isGeneratorIng = false;

        if (m_grabbedObj != null)
        {
            OVRPose localPose = new OVRPose {
                position = OVRInput.GetLocalControllerPosition(m_controller), orientation = OVRInput.GetLocalControllerRotation(m_controller)
            };
            OVRPose offsetPose = new OVRPose {
                position = m_anchorOffsetPosition, orientation = m_anchorOffsetRotation
            };
            localPose = localPose * offsetPose;

            OVRPose trackingSpace   = transform.ToOVRPose() * localPose.Inverse();
            Vector3 linearVelocity  = trackingSpace.orientation * OVRInput.GetLocalControllerVelocity(m_controller);
            Vector3 angularVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerAngularVelocity(m_controller);

            GrabbableRelease(linearVelocity, angularVelocity);
        }

        // Re-enable grab volumes to allow overlap events
        GrabVolumeEnable(true);
    }
示例#30
0
        void Update()
        {
            activeController = OVRInputHelpers.GetControllerForButton(OVRInput.Button.PrimaryIndexTrigger, activeController);
            Ray pointer = OVRInputHelpers.GetSelectionRay(activeController, trackingSpace);

            RaycastHit hit; // Was anything hit?

            if (Physics.Raycast(pointer, out hit, raycastDistance, ~excludeLayers))
            {
                myHitPos = hit.point;
                myOVRPointerVisualizer.rayDrawDistance = hit.distance;
                //Debug.Log(hit.distance);


                if (lastHit != null && lastHit != hit.transform)
                {
                    if (onHoverExit != null)
                    {
                        onHoverExit.Invoke(lastHit);
                    }
                    lastHit = null;
                }

                if (lastHit == null)
                {
                    if (onHoverEnter != null)
                    {
                        onHoverEnter.Invoke(hit.transform);
                    }
                }

                if (onHover != null)
                {
                    onHover.Invoke(hit.transform);
                }

                lastHit = hit.transform;

                // Handle selection callbacks. An object is selected if the button selecting it was
                // pressed AND released while hovering over the object.

                if (activeController != OVRInput.Controller.None)
                {
                    if (OVRInput.GetDown(secondaryButton, activeController))
                    {
                        secondaryDown = lastHit;
                        //Debug.Log("1");
                    }
                    else if (OVRInput.GetUp(secondaryButton, activeController))
                    {
                        if (secondaryDown != null && secondaryDown == lastHit)
                        {
                            if (onSecondarySelect != null)
                            {
                                onSecondarySelect.Invoke(secondaryDown, pointer);
                                //Debug.Log("2");
                            }
                        }
                    }
                    if (!OVRInput.Get(secondaryButton, activeController))
                    {
                        secondaryDown = null;
                        //Debug.Log("3");
                    }

                    if (OVRInput.GetDown(primaryButton, activeController))
                    {
                        primaryDown = lastHit;
                        //Debug.Log("4");
                    }
                    else if (OVRInput.GetUp(primaryButton, activeController))
                    {
                        if (primaryDown != null && primaryDown == lastHit)
                        {
                            if (onPrimarySelect != null)
                            {
                                onPrimarySelect.Invoke(primaryDown, pointer);
                                //Debug.Log("5");
                            }
                        }
                    }
                    if (!OVRInput.Get(primaryButton, activeController))
                    {
                        primaryDown = null;
                        //Debug.Log("6");
                    }
                }

                if (lastHit)
                {
                    ///
                    if (OVRInput.Get(aButton, activeController))
                    {
                        aDown = lastHit;
                    }
                    else
                    {
                        aDown = null;
                    }
                    if (OVRInput.Get(bButton, activeController))
                    {
                        bDown = lastHit;
                    }
                    else
                    {
                        bDown = null;
                    }
                }



                if (aDown)
                {
                    //Debug.Log("A---->" + aDown);
                    onHoverADown.Invoke(aDown);
                }

                if (bDown)
                {
                    //Debug.Log("B---->" + bDown);
                    onHoverBDown.Invoke(bDown);
                }

                if (primaryDown && !secondaryDown)
                {
                    //Debug.Log(primaryDown);
                    //Debug.Log(axisValue);
                    if (!tractorBeaming)
                    {
                        tractorBeaming           = true;
                        tractorTime              = 0.0f;
                        tractorAxisInputFiltered = 0.0f;
                    }
                    else
                    {
                        tractorTime += Time.deltaTime;
                        if (tractorTime > tractorDelay)
                        {
                            float axisValue = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, activeController);
                            tractorAxisInputFiltered = Mathf.Lerp(tractorAxisInputFiltered, axisValue, tractorLerp);
                            onPrimarySelectDownAxis.Invoke(primaryDown, pointer, tractorAxisInputFiltered);
                        }
                    }
                }
                else if (secondaryDown && !primaryDown)
                {
                    //Debug.Log(secondaryDown);
                    //Debug.Log(axisValue);
                    if (!tractorBeaming)
                    {
                        tractorBeaming           = true;
                        tractorTime             += Time.deltaTime;
                        tractorAxisInputFiltered = 0.0f;
                    }
                    else
                    {
                        tractorTime++;
                        if (tractorTime > tractorDelay)
                        {
                            float axisValue = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, activeController);
                            tractorAxisInputFiltered = Mathf.Lerp(tractorAxisInputFiltered, axisValue, tractorLerp);
                            onSecondarySelectDownAxis.Invoke(secondaryDown, pointer, tractorAxisInputFiltered);
                        }
                    }
                }
                else
                {
                    tractorBeaming = false;
                }

#if UNITY_ANDROID && !UNITY_EDITOR
                // Gaze pointer fallback
                else
                {
                    if (Input.GetMouseButtonDown(0))
                    {
                        triggerDown = lastHit;
                    }
                    else if (Input.GetMouseButtonUp(0))
                    {
                        if (triggerDown != null && triggerDown == lastHit)
                        {
                            if (onPrimarySelect != null)
                            {
                                onPrimarySelect.Invoke(triggerDown);
                            }
                        }
                    }
                    if (!Input.GetMouseButton(0))
                    {
                        triggerDown = null;
                    }
                }
#endif

                //REMOTE GRAB
                if (!remoteGrab)
                {
                    // remoteGrab not set - looking for candidate
                    if (lastHit)
                    {
                        if (primaryDown && secondaryDown)
                        {
                            if (lastHit == primaryDown && lastHit == secondaryDown)
                            {
                                // START remote grabbing
                                //Debug.Log(lastHit + " is candidate for remoteGrab");
                                remoteGrab = lastHit;
                                // initially set remoteGrabTargetDistance to hit.distance
                                remoteGrabTargetDistance = hit.distance;
                                remoteGrabHitOffset      = remoteGrab.position - hit.point;
                                //Debug.Log("   --->" + hit.distance);
                                remoteGrabStartPos  = hit.point;
                                approxMovingAvgPoke = 0f;
                                remoteGrabTime      = 0.0f;

                                remoteGrabObjectStartQ     = remoteGrab.gameObject.transform.rotation;
                                remoteGrabControllerStartQ = OVRInput.GetLocalControllerRotation(activeController);

                                BackboneUnit bu = (remoteGrab.gameObject.GetComponent("BackboneUnit") as BackboneUnit);
                                if (bu != null)
                                {
                                    bu.SetRemoteGrabSelect(true);
                                    //bu.remoteGrabSelectOn = true;
                                    //bu.UpdateRenderMode();
                                }

                                //Rigidbody hitRigidBody = lastHit.gameObject.GetComponent<Rigidbody>();
                                //remoteGrabOffset = hitRigidBody.position - hit.point;
                            }
                        }
                    }
                }
                else
                {
                }
            }