Esempio n. 1
0
 // Start is called before the first frame update
 void Start()
 {
     activeController = OVRInput.Controller.RTrackedRemote;
 }
Esempio n. 2
0
    private void Update()
    {
        OVRInput.Controller activeController = OVRInput.GetActiveController();
        this.data.Length = 0;
        byte controllerRecenterCount = OVRInput.GetControllerRecenterCount(OVRInput.Controller.Active);

        this.data.AppendFormat("RecenterCount: {0}\n", controllerRecenterCount);
        byte controllerBatteryPercentRemaining = OVRInput.GetControllerBatteryPercentRemaining(OVRInput.Controller.Active);

        this.data.AppendFormat("Battery: {0}\n", controllerBatteryPercentRemaining);
        float appFramerate = OVRPlugin.GetAppFramerate();

        this.data.AppendFormat("Framerate: {0:F2}\n", appFramerate);
        string arg = activeController.ToString();

        this.data.AppendFormat("Active: {0}\n", arg);
        string arg2 = OVRInput.GetConnectedControllers().ToString();

        this.data.AppendFormat("Connected: {0}\n", arg2);
        this.data.AppendFormat("PrevConnected: {0}\n", OVRGearVrControllerTest.prevConnected);
        OVRGearVrControllerTest.controllers.Update();
        OVRGearVrControllerTest.controllers.AppendToStringBuilder(ref this.data);
        OVRGearVrControllerTest.prevConnected = arg2;
        Quaternion localControllerRotation = OVRInput.GetLocalControllerRotation(activeController);

        this.data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", new object[]
        {
            localControllerRotation.x,
            localControllerRotation.y,
            localControllerRotation.z,
            localControllerRotation.w
        });
        Vector3 localControllerAngularVelocity = OVRInput.GetLocalControllerAngularVelocity(activeController);

        this.data.AppendFormat("AngVel: ({0:F2}, {1:F2}, {2:F2})\n", localControllerAngularVelocity.x, localControllerAngularVelocity.y, localControllerAngularVelocity.z);
        Vector3 localControllerAngularAcceleration = OVRInput.GetLocalControllerAngularAcceleration(activeController);

        this.data.AppendFormat("AngAcc: ({0:F2}, {1:F2}, {2:F2})\n", localControllerAngularAcceleration.x, localControllerAngularAcceleration.y, localControllerAngularAcceleration.z);
        Vector3 localControllerPosition = OVRInput.GetLocalControllerPosition(activeController);

        this.data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", localControllerPosition.x, localControllerPosition.y, localControllerPosition.z);
        Vector3 localControllerVelocity = OVRInput.GetLocalControllerVelocity(activeController);

        this.data.AppendFormat("Vel: ({0:F2}, {1:F2}, {2:F2})\n", localControllerVelocity.x, localControllerVelocity.y, localControllerVelocity.z);
        Vector3 localControllerAcceleration = OVRInput.GetLocalControllerAcceleration(activeController);

        this.data.AppendFormat("Acc: ({0:F2}, {1:F2}, {2:F2})\n", localControllerAcceleration.x, localControllerAcceleration.y, localControllerAcceleration.z);
        Vector2 vector = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad, OVRInput.Controller.Active);

        this.data.AppendFormat("PrimaryTouchpad: ({0:F2}, {1:F2})\n", vector.x, vector.y);
        Vector2 vector2 = OVRInput.Get(OVRInput.Axis2D.SecondaryTouchpad, OVRInput.Controller.Active);

        this.data.AppendFormat("SecondaryTouchpad: ({0:F2}, {1:F2})\n", vector2.x, vector2.y);
        float num = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.Active);

        this.data.AppendFormat("PrimaryIndexTriggerAxis1D: ({0:F2})\n", num);
        float num2 = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.Active);

        this.data.AppendFormat("PrimaryHandTriggerAxis1D: ({0:F2})\n", num2);
        for (int i = 0; i < this.monitors.Count; i++)
        {
            this.monitors[i].Update();
            this.monitors[i].AppendToStringBuilder(ref this.data);
        }
        if (this.uiText != null)
        {
            this.uiText.text = this.data.ToString();
        }
    }
Esempio n. 3
0
    ControllerPose GetControllerPose(OVRInput.Controller controller)
    {
        ovrAvatarButton buttons = 0;

        if (OVRInput.Get(OVRInput.Button.One, controller))
        {
            buttons |= ovrAvatarButton.One;
        }
        if (OVRInput.Get(OVRInput.Button.Two, controller))
        {
            buttons |= ovrAvatarButton.Two;
        }
        if (OVRInput.Get(OVRInput.Button.Start, controller))
        {
            buttons |= ovrAvatarButton.Three;
        }
        if (OVRInput.Get(OVRInput.Button.PrimaryThumbstick, controller))
        {
            buttons |= ovrAvatarButton.Joystick;
        }

        ovrAvatarTouch touches = 0;

        if (OVRInput.Get(OVRInput.Touch.One, controller))
        {
            touches |= ovrAvatarTouch.One;
        }
        if (OVRInput.Get(OVRInput.Touch.Two, controller))
        {
            touches |= ovrAvatarTouch.Two;
        }
        if (OVRInput.Get(OVRInput.Touch.PrimaryThumbstick, controller))
        {
            touches |= ovrAvatarTouch.Joystick;
        }
        if (OVRInput.Get(OVRInput.Touch.PrimaryThumbRest, controller))
        {
            touches |= ovrAvatarTouch.ThumbRest;
        }
        if (OVRInput.Get(OVRInput.Touch.PrimaryIndexTrigger, controller))
        {
            touches |= ovrAvatarTouch.Index;
        }
        if (!OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, controller))
        {
            touches |= ovrAvatarTouch.Pointing;
        }
        if (!OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, controller))
        {
            touches |= ovrAvatarTouch.ThumbUp;
        }

        return(new ControllerPose
        {
            buttons = buttons,
            touches = touches,
            joystickPosition = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, controller),
            indexTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller),
            handTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, controller),
            isActive = (OVRInput.GetActiveController() & controller) != 0,
        });
    }
Esempio n. 4
0
 public void Grab(OVRInput.Controller grabHand)
 {
     controllerHand = grabHand;
 }
Esempio n. 5
0
 public VRControllerInputOculus Init(Handedness handy)
 {
     handedness     = handy;
     controllerType = (handy == Handedness.Left) ? OVRInput.Controller.LTouch : OVRInput.Controller.RTouch;
     return(this);
 }
Esempio n. 6
0
    void Start()
    {
        OVRPlugin.SystemHeadset headset = OVRPlugin.GetSystemHeadsetType();
        switch (headset)
        {
        case OVRPlugin.SystemHeadset.Oculus_Go:
            activeControllerType = ControllerType.Go;
            break;

        case OVRPlugin.SystemHeadset.Oculus_Quest:
            activeControllerType = ControllerType.QuestAndRiftS;
            break;

        case OVRPlugin.SystemHeadset.Rift_CV1:
            activeControllerType = ControllerType.Rift;
            break;

        case OVRPlugin.SystemHeadset.Rift_S:
        case OVRPlugin.SystemHeadset.Oculus_Link_Quest:
            activeControllerType = ControllerType.QuestAndRiftS;
            break;

        case OVRPlugin.SystemHeadset.GearVR_R320:
        case OVRPlugin.SystemHeadset.GearVR_R321:
        case OVRPlugin.SystemHeadset.GearVR_R322:
        case OVRPlugin.SystemHeadset.GearVR_R323:
        case OVRPlugin.SystemHeadset.GearVR_R324:
        case OVRPlugin.SystemHeadset.GearVR_R325:
            activeControllerType = ControllerType.GearVR;
            break;

        default:
#if UNITY_EDITOR || !UNITY_ANDROID
            activeControllerType = ControllerType.Rift;
#else
            activeControllerType = ControllerType.GearVR;
#endif
            break;
        }

        Debug.LogFormat("OVRControllerHelp: Active controller type: {0} for product {1}", activeControllerType, OVRPlugin.productName);
        if ((activeControllerType != ControllerType.GearVR) && (activeControllerType != ControllerType.Go))
        {
            if (m_controller == OVRInput.Controller.LTrackedRemote)
            {
                m_controller = OVRInput.Controller.LTouch;
            }
            else if (m_controller == OVRInput.Controller.RTrackedRemote)
            {
                m_controller = OVRInput.Controller.RTouch;
            }
        }
        else
        {
            if (m_controller == OVRInput.Controller.LTouch)
            {
                m_controller = OVRInput.Controller.LTrackedRemote;
            }
            else if (m_controller == OVRInput.Controller.RTouch)
            {
                m_controller = OVRInput.Controller.RTrackedRemote;
            }
        }
    }
Esempio n. 7
0
        public void VibrateFor(float vibrationDuration, float vibrationFrequence, float vibrationAmplitude, OVRInput.Controller controller)
        {
            if (isVibrating)
            {
                return;
            }

            if (UnityEngine.XR.XRDevice.model != "Oculus Quest")
            {
                return;
            }

            OVRInput.SetControllerVibration(vibrationFrequence, vibrationAmplitude, controller);
            StartCoroutine(stopVibrationCoroutine(vibrationDuration, controller));
        }
    /// <summary>
    /// Based on the input mode, controller state, and current intention of the teleport controller, return the apparent intention of the user.
    /// </summary>
    /// <returns></returns>
    public override LocomotionTeleport.TeleportIntentions GetIntention()
    {
        if (!isActiveAndEnabled)
        {
            return(global::LocomotionTeleport.TeleportIntentions.None);
        }

        // If capacitive touch isn't being used, the base implementation will do the work.
        if (InputMode == InputModes.SeparateButtonsForAimAndTeleport)
        {
            return(base.GetIntention());
        }

        // ThumbstickTeleport will begin aiming when the thumbstick is pushed.
        if (InputMode == InputModes.ThumbstickTeleport || InputMode == InputModes.ThumbstickTeleportForwardBackOnly)
        {
            // Note there's a bit of wasted work here if you're only using 1 thumbstick to trigger teleport.
            // Feel free to delete the extra code for the unnecessary stick.
            Vector2             leftStick      = OVRInput.Get(OVRInput.RawAxis2D.LThumbstick);
            Vector2             rightStick     = OVRInput.Get(OVRInput.RawAxis2D.RThumbstick);
            float               leftMag        = 0.0f;
            float               rightMag       = 0.0f;
            float               bestMag        = 0.0f;
            OVRInput.Controller bestController = OVRInput.Controller.Touch;
            bool leftTouched  = OVRInput.Get(OVRInput.RawTouch.LThumbstick);
            bool rightTouched = OVRInput.Get(OVRInput.RawTouch.RThumbstick);

            if (InputMode == InputModes.ThumbstickTeleportForwardBackOnly && LocomotionTeleport.CurrentIntention != LocomotionTeleport.TeleportIntentions.Aim)
            {
                // If user is aiming, ThumbstickTeleport and ThumbstickTeleportForwardBackOnly are identical. But if not, we only want magnitude along the forward or back vector.
                leftMag  = Mathf.Abs(Vector2.Dot(leftStick, Vector2.up));
                rightMag = Mathf.Abs(Vector2.Dot(rightStick, Vector2.up));
            }
            else
            {
                leftMag  = leftStick.magnitude;
                rightMag = rightStick.magnitude;
            }
            if (AimingController == OVRInput.Controller.LTouch)
            {
                bestMag        = leftMag;
                bestController = OVRInput.Controller.LTouch;
            }
            else if (AimingController == OVRInput.Controller.RTouch)
            {
                bestMag        = rightMag;
                bestController = OVRInput.Controller.RTouch;
            }
            else
            {
                if (leftMag > rightMag)
                {
                    bestMag        = leftMag;
                    bestController = OVRInput.Controller.LTouch;
                }
                else
                {
                    bestMag        = rightMag;
                    bestController = OVRInput.Controller.RTouch;
                }
            }

            bool touching = bestMag > ThumbstickTeleportThreshold ||
                            (AimingController == OVRInput.Controller.Touch && (leftTouched || rightTouched)) ||
                            (AimingController == OVRInput.Controller.LTouch && leftTouched) ||
                            (AimingController == OVRInput.Controller.RTouch && rightTouched);
            if (!touching)
            {
                if (LocomotionTeleport.CurrentIntention == LocomotionTeleport.TeleportIntentions.Aim)
                {
                    // If the user has released the thumbstick, enter the PreTeleport state unless FastTeleport is enabled,
                    // in which case enter the Teleport state.
                    return(FastTeleport ? LocomotionTeleport.TeleportIntentions.Teleport : LocomotionTeleport.TeleportIntentions.PreTeleport);
                }

                // If the user is already in the preteleport state, the intention will be to either remain in this state or switch to Teleport
                if (LocomotionTeleport.CurrentIntention == LocomotionTeleport.TeleportIntentions.PreTeleport)
                {
                    return(LocomotionTeleport.TeleportIntentions.Teleport);
                }
            }
            else
            {
                if (LocomotionTeleport.CurrentIntention == LocomotionTeleport.TeleportIntentions.Aim)
                {
                    return(LocomotionTeleport.TeleportIntentions.Aim);
                }
            }

            if (bestMag > ThumbstickTeleportThreshold)
            {
                InitiatingController = bestController;
                return(LocomotionTeleport.TeleportIntentions.Aim);
            }

            return(LocomotionTeleport.TeleportIntentions.None);
        }

        // Capacitive touch logic is essentially the same as the base logic, except the button types are different
        // so different methods need to be used.
        var teleportButton = _rawButtons[(int)CapacitiveAimAndTeleportButton];

        if (LocomotionTeleport.CurrentIntention == LocomotionTeleport.TeleportIntentions.Aim)
        {
            // If the user has actually pressed the teleport button, enter the preteleport state.
            if (OVRInput.GetDown(teleportButton))
            {
                // If the user has released the thumbstick, enter the PreTeleport state unless FastTeleport is enabled,
                // in which case enter the Teleport state.
                return(FastTeleport ? LocomotionTeleport.TeleportIntentions.Teleport : LocomotionTeleport.TeleportIntentions.PreTeleport);
            }
        }

        // If the user is already in the PreTeleport state, the intention will be to either remain in this state or switch to Teleport
        if (LocomotionTeleport.CurrentIntention == LocomotionTeleport.TeleportIntentions.PreTeleport)
        {
            // If they released the button, switch to Teleport.
            if (FastTeleport || OVRInput.GetUp(teleportButton))
            {
                // Button released, enter the Teleport state.
                return(LocomotionTeleport.TeleportIntentions.Teleport);
            }
            // Button still down, remain in PreTeleport so they can orient the destination if an orientation handler supports it.
            return(LocomotionTeleport.TeleportIntentions.PreTeleport);
        }

        // If it made it this far, then we need to determine if the user intends to be aiming with the capacitive touch.
        // The first check is if cap touch has been triggered.
        if (OVRInput.GetDown(_rawTouch[(int)CapacitiveAimAndTeleportButton]))
        {
            return(LocomotionTeleport.TeleportIntentions.Aim);
        }

        if (LocomotionTeleport.CurrentIntention == LocomotionTeleport.TeleportIntentions.Aim)
        {
            if (!OVRInput.GetUp(_rawTouch[(int)CapacitiveAimAndTeleportButton]))
            {
                return(LocomotionTeleport.TeleportIntentions.Aim);
            }
        }

        return(LocomotionTeleport.TeleportIntentions.None);
    }
Esempio n. 9
0
    public static void Trigger(AudioClip vibrationAudio, OVRInput.Controller controller)
    {
        OVRHapticsClip clip = new OVRHapticsClip(vibrationAudio);

        VibeOnCorrespondingController(clip, controller);
    }
    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();
        }
    }
        void Update()
        {
            // The scroll view has a viewport that masks the UI that is outside the scroll view.
            // However, it does not filter any ray casting that is outside the mask!
            // This means that the box colliders of the individual cells still get hit outside the scroll view itself,
            // which can interfer with the tabs above the scroll view.
            //
            // To fix this issue, we cast a ray from current pointer to the scroll view's box collider.
            // If we get a hit, it means we're inside the scroll view - so we enable all the children box
            // colliders, which will behave as expected.
            // If we do not get a hit, it means that we're outside the scroll view - so we disable all the children
            // box colliders, which addresses the issue above.
            this.activeController = OVRInputHelpers.GetControllerForButton(OVRInput.Button.PrimaryIndexTrigger, this.activeController);
            Ray pointer = OVRInputHelpers.GetSelectionRay(this.activeController, this.trackingSpace);

            RaycastHit hit;

            if (this.boxCollider.Raycast(pointer, out hit, 500))
            {
                // We got a hit in the scroll view. Check if we're already within the bounds - if so, do nothing.
                if (!isInBounds)
                {
                    // We entered the scroll view, so enable box colliders on children.
                    foreach (var boxCollider in this.content.gameObject.GetComponentsInChildren <BoxCollider>())
                    {
                        boxCollider.enabled = true;
                    }

                    isInBounds = true;
                }
            }
            else if (isInBounds)
            {
                // We are outside the scroll view and were previously inside, so disable box colliders on children.
                foreach (var boxCollider in this.content.gameObject.GetComponentsInChildren <BoxCollider>())
                {
                    boxCollider.enabled = false;
                }

                isInBounds = false;
            }

            // Get vector from either left or right thumbstick
            var moveVector = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);

            if (moveVector.x == 0 && moveVector.y == 0)
            {
                moveVector = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
            }
            if (moveVector.x == 0 && moveVector.y == 0)
            {
                moveVector = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad);
            }
            if (moveVector.x == 0 && moveVector.y == 0)
            {
                moveVector = OVRInput.Get(OVRInput.Axis2D.SecondaryTouchpad);
            }

            if (moveVector.y == 0)
            {
                // No y-movement, so return. Also reset the speed multiplier
                this.lastSpeedMultiplier = 0;
                return;
            }

            // Scroll by a fixed amount proportional to thumbstick position on each frame
            // and map this to a fraction of the total viewport size:
            //   moveVector.y: The thumbstick vertical position normalized to [-1,1].
            //   Time.deltaTime: The time delta since last frame
            //   speedMultiplier: Just a multiplier to get a good scrolling speed. Increase over time to speed up scrolling.
            // So, moveVector.y * Time.deltaTime * speedMultiplier = the amount to scroll in "units"
            //   proportional to thumbstick position since last frame.
            // this.cellHeight / this.content.sizeDelta.y = cell height / total content height.
            float speedMultiplier   = Mathf.Clamp(this.lastSpeedMultiplier * SpeedMultiplierIncrease, SpeedMultiplier, MaxSpeedMultiplier);
            float verticalIncrement = moveVector.y * Time.deltaTime * speedMultiplier * this.cellHeight / this.content.sizeDelta.y;

            this.lastSpeedMultiplier        = speedMultiplier;
            this.verticalNormalizedPosition = Mathf.Clamp01(this.verticalNormalizedPosition + verticalIncrement);
        }
Esempio n. 12
0
    // 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;
        }
    }
    IEnumerator StopVibration(float _time, OVRInput.Controller _contr)
    {
        yield return(new WaitForSeconds(_time));

        OVRInput.SetControllerVibration(0, 0, _contr);
    }
 public void TriggerVibration(int millis, OVRInput.Controller controller)
 {
     StopAllCoroutines();
     OVRInput.SetControllerVibration(0.8f, 1, controller);
     StartCoroutine(StopVibration(millis / 1000, controller));
 }
Esempio n. 15
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));
 }
Esempio n. 16
0
 void Start()
 {
     controller = (hand == HandType.left) ? OVRInput.Controller.LTouch : OVRInput.Controller.RTouch;
     ball       = GameObject.FindGameObjectWithTag("ball").GetComponent <Pickupable>();
 }
Esempio n. 17
0
 public void releaseFunction(OVRInput.Controller hand)
 {
     releaseFunctionConcrete(OVRInput.GetLocalControllerPosition(hand), getWorldPosition(hand), OVRInput.GetLocalControllerRotation(hand), getWorldRotation(hand));
 }
    public override void UpdateMovement()
    {
        bool HaltUpdateMovement = false;

        GetHaltUpdateMovement(ref HaltUpdateMovement);
        if (HaltUpdateMovement)
        {
            return;
        }

        float MoveScaleMultiplier = 1;

        GetMoveScaleMultiplier(ref MoveScaleMultiplier);

        float RotationScaleMultiplier = 1;

        GetRotationScaleMultiplier(ref RotationScaleMultiplier);

        bool SkipMouseRotation = false;

        GetSkipMouseRotation(ref SkipMouseRotation);

        float MoveScale = 1.0f;

        // No positional movement if we are in the air
        if (!Controller.isGrounded)
        {
            MoveScale = 0.0f;
        }

        MoveScale *= SimulationRate_ * Time.deltaTime;



        Quaternion playerDirection = ((HmdRotatesY) ? CameraRig.centerEyeAnchor.rotation : transform.rotation);

        //remove any pitch + yaw components
        playerDirection = Quaternion.Euler(0, playerDirection.eulerAngles.y, 0);

        Vector3 euler = transform.rotation.eulerAngles;

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

        bool stepLeft  = false;
        bool stepRight = false;

        stepLeft  = OVRInput.GetDown(OVRInput.Button.PrimaryShoulder) || Input.GetKeyDown(KeyCode.Q);
        stepRight = OVRInput.GetDown(OVRInput.Button.SecondaryShoulder) || Input.GetKeyDown(KeyCode.E);

        OVRInput.Controller activeController = OVRInput.GetActiveController();
        if ((activeController == OVRInput.Controller.Touchpad) ||
            (activeController == OVRInput.Controller.Remote))
        {
            stepLeft  |= OVRInput.GetDown(OVRInput.Button.DpadLeft);
            stepRight |= OVRInput.GetDown(OVRInput.Button.DpadRight);
        }
        else if ((activeController == OVRInput.Controller.LTrackedRemote) ||
                 (activeController == OVRInput.Controller.RTrackedRemote))
        {
            if (OVRInput.GetDown(OVRInput.Button.PrimaryTouchpad))
            {
                if ((touchDir.magnitude > 0.3f) &&
                    (Mathf.Abs(touchDir.x) > Mathf.Abs(touchDir.y)))
                {
                    stepLeft  |= (touchDir.x < 0.0f);
                    stepRight |= (touchDir.x > 0.0f);
                }
            }
        }

        float rotateInfluence = SimulationRate_ * Time.deltaTime * RotationAmount * RotationScaleMultiplier;

#if !UNITY_ANDROID
        if (!SkipMouseRotation)
        {
            PendingRotation += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f;
        }
#endif
        float rightAxisX = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick).x;
        if (Mathf.Abs(rightAxisX) < axisDeadZone)
        {
            rightAxisX = 0;
        }

        PendingRotation += rightAxisX * rotateInfluence;


        if (rotationSnap)
        {
            if (Mathf.Abs(PendingRotation) > RotationRatchet)
            {
                if (PendingRotation > 0)
                {
                    stepRight = true;
                }
                else
                {
                    stepLeft = true;
                }
                PendingRotation -= Mathf.Sign(PendingRotation) * RotationRatchet;
            }
        }
        else
        {
            euler.y        += PendingRotation;
            PendingRotation = 0;
        }



        if (rotationAnimation > 0 && animating)
        {
            float speed = Mathf.Max(rotationAnimation, 3);

            float diff = AngleDifference(targetYaw, euler.y);
            // float done = AngleDifference(euler.y, animationStartAngle);

            euler.y += Mathf.Sign(diff) * speed * Time.deltaTime;

            if ((AngleDifference(targetYaw, euler.y) < 0) != (diff < 0))
            {
                animating = false;
                euler.y   = targetYaw;
            }
        }
        if (stepLeft ^ stepRight)
        {
            float change = stepRight ? RotationRatchet : -RotationRatchet;

            if (rotationAnimation > 0)
            {
                targetYaw = (euler.y + change) % 360;
                animating = true;
                // animationStartAngle = euler.y;
            }
            else
            {
                euler.y += change;
            }
        }

        float moveInfluence = SimulationRate_ * Time.deltaTime * Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;

        // Run!
        if (OVRInput.Get(runButton) || OVRInput.Get(alternateRunButton) || Input.GetKey(KeyCode.LeftShift))
        {
            moveInfluence *= 2.0f;
        }


        float leftAxisX = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick).x;
        float leftAxisY = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick).y;

        if (activeController == OVRInput.Controller.Touchpad)
        {
            leftAxisY = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad).y;
        }
        else if ((activeController == OVRInput.Controller.LTrackedRemote) ||
                 (activeController == OVRInput.Controller.RTrackedRemote))
        {
            if (OVRInput.Get(OVRInput.Button.PrimaryTouchpad))
            {
                if ((touchDir.magnitude > 0.3f) &&
                    (Mathf.Abs(touchDir.y) > Mathf.Abs(touchDir.x)))
                {
                    leftAxisY = (touchDir.y > 0.0f) ? 1 : -1;
                }
            }
        }

        if (Mathf.Abs(leftAxisX) < axisDeadZone)
        {
            leftAxisX = 0;
        }
        if (Mathf.Abs(leftAxisY) < axisDeadZone)
        {
            leftAxisY = 0;
        }

        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            leftAxisY = 1;
        }
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            leftAxisX = -1;
        }
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            leftAxisX = 1;
        }
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            leftAxisY = -1;
        }

        if (activeController == OVRInput.Controller.Remote)
        {
            if (OVRInput.Get(OVRInput.Button.DpadUp))
            {
                leftAxisY = 1;
            }
            else if (OVRInput.Get(OVRInput.Button.DpadDown))
            {
                leftAxisY = -1;
            }
        }

        if (leftAxisY > 0.0f)
        {
            MoveThrottle_ += leftAxisY
                             * (playerDirection * (Vector3.forward * moveInfluence));
        }

        if (leftAxisY < 0.0f)
        {
            MoveThrottle_ += Mathf.Abs(leftAxisY)
                             * (playerDirection * (Vector3.back * moveInfluence));
        }

        if (leftAxisX < 0.0f)
        {
            MoveThrottle_ += Mathf.Abs(leftAxisX)
                             * (playerDirection * (Vector3.left * moveInfluence));
        }

        if (leftAxisX > 0.0f)
        {
            MoveThrottle_ += leftAxisX
                             * (playerDirection * (Vector3.right * moveInfluence));
        }

        transform.rotation = Quaternion.Euler(euler);
    }
Esempio n. 19
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;
            bool    isGripPressed;
            Vector2 stickInput;

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

            bool isSelecting = isTriggerPressed || isGripPressed;

            UpdateCustomTeleportPointer(stickInput, worldPosition, worldRotation);

            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 = isSelecting;

                    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 = isSelecting;

                    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;
                }
            }
        }
Esempio n. 20
0
 private bool OnButtonUp(OVRInput.Button button, OVRInput.Controller controller)
 {
     return(OVRInput.GetUp(button, controller));
 }
Esempio n. 21
0
    void Disparar(OVRInput.Controller controlador)
    {
        VibracionManager.vibracion(30, 2, 255, controlador);


        //Colisiona con solo el ultimo numero
        int layerMask = 1 << 14;

        //Invierte y da a todos menos al ultimo numero
        layerMask = ~layerMask;

        //EMPUJE OBJETO COLISIONADO CON BALA
        if (Physics.Raycast(salidaBala.position, transform.TransformDirection(Vector3.right), out RaycastHit hit, 500, layerMask))
        {
            if (hit.transform.gameObject.GetComponent <Rigidbody>())
            {
                Rigidbody rb = hit.transform.gameObject.GetComponent <Rigidbody>();
                rb.AddForce(salidaBala.forward * 500);

                if (hit.transform.gameObject.GetComponent <Rompible>())
                {
                    hit.transform.gameObject.GetComponent <Rompible>().cambiar();
                }
                else
                {
                    //PARTICULAS COLISION DECORADO
                    Instantiate(chispasImpacto, hit.point, Quaternion.identity);
                }

                if (hit.transform.gameObject.GetComponent <diana>())
                {
                    hit.transform.gameObject.GetComponent <diana>().golpeo();
                }
                else if (hit.transform.gameObject.GetComponent <pirata>())
                {
                    hit.transform.gameObject.GetComponent <pirata>().golpe();
                }
            }
        }


        //CASQUETES
        GameObject casqueteNuevo = Instantiate(casquete, salidaCasquete.position, Quaternion.identity, salidaCasquete);
        Rigidbody  rbCn          = casqueteNuevo.GetComponent <Rigidbody>();

        rbCn.AddForce(salidaCasquete.forward * Random.Range(125f, 225f));
        rbCn.maxAngularVelocity = 1000;
        casqueteNuevo.transform.SetParent(null);
        Destroy(casqueteNuevo, 4);


        //TExtoBalas
        setBalasTexto(true);


        //Animacion
        animator.Play("disparo", -1, 0f);

        //Efectos
        fuegoDisparo.Play();
        audioSource.Play();
    }
Esempio n. 22
0
 private Vector2 OnAxis(OVRInput.Axis2D axis, OVRInput.Controller controller)
 {
     return(OVRInput.Get(axis, controller));
 }
Esempio n. 23
0
 public void Release()
 {
     controllerHand = OVRInput.Controller.None;
 }
Esempio n. 24
0
    public static void Update()
    {
#if UNITY_EDITOR || !UNITY_ANDROID
        if (simulateController != OVRInput.Controller.LTrackedRemote && simulateController != OVRInput.Controller.RTrackedRemote && simulateController != OVRInput.Controller.LTouch && simulateController != OVRInput.Controller.RTouch)
        {
            // Default to a right handed controller if not set!
            simulateController = OVRInput.Controller.RTrackedRemote;
        }
        UnityEngine.XR.XRNode handNode = (simulateController == OVRInput.Controller.LTouch || simulateController == OVRInput.Controller.LTrackedRemote) ? UnityEngine.XR.XRNode.LeftHand : UnityEngine.XR.XRNode.RightHand;

        OVRPose remotePoseWithoutPosition = new OVRPose();
        remotePoseWithoutPosition.orientation = ConvertHandedness(UnityEngine.XR.InputTracking.GetLocalRotation(handNode));
        remotePoseWithoutPosition.position    = new Vector3(0.0f, 0.0f, 0.0f);

        OVRPose headPoseWithoutPosition = new OVRPose();
        headPoseWithoutPosition.orientation = ConvertHandedness(UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.Head));

#if UNITY_ANDROID && !UNITY_EDITOR
        // Running on Gear VR, the head position is not needed
        headPoseWithoutPosition.position = new Vector3(0.0f, 0.0f, 0.0f);
#else
        // Running on Rift, the head position is needed
        headPoseWithoutPosition.position = ConvertHandedness(UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.Head));
#endif

        OVRPose remotePose = new OVRPose();
        ovrArmModel.Update(headPoseWithoutPosition, remotePoseWithoutPosition, handNode, OVRPlugin.shouldRecenter, out remotePose);

        localRotation = ConvertHandedness(remotePose.orientation);
        localPosition = ConvertHandedness(remotePose.position);
#endif

        if (BackClicked && OnBackClicked != null)
        {
            OnBackClicked();
        }

        if (lastTriggerState && !TriggerDown && OnTriggerUp != null)
        {
            OnTriggerUp();
        }
        else if (!lastTriggerState && TriggerDown && OnTriggerDown != null)
        {
            OnTriggerDown();
        }

        if (lastTouchpadState && !TouchpadDown && OnTouchpadUp != null)
        {
            OnTouchpadUp();
        }
        else if (!lastTriggerState && TouchpadDown && OnTouchpadDown != null)
        {
            OnTouchpadDown();
        }

        if (TouchpadTouched && OnTouch != null)
        {
            OnTouch(TouchpadPosition);
        }

        lastTriggerState  = TriggerDown;
        lastTouchpadState = TouchpadDown;
    }
Esempio n. 25
0
 bool IsButtonDownOnController(OVRInput.Controller cont, OVRInput.Controller cont2 = OVRInput.Controller.None)
 {
     return(OVRInput.GetDown(CurvedUIInputModule.Instance.OculusTouchInteractionButton, cont) || (cont2 != OVRInput.Controller.None && OVRInput.GetDown(CurvedUIInputModule.Instance.OculusTouchInteractionButton, cont2)));
 }
Esempio n. 26
0
 void Start()
 {
     // OVRControllerHelperから左右どっちかを取得する
     controller = GetComponent <OVRControllerHelper>().m_controller;
 }
Esempio n. 27
0
    void Update()
    {
        if (!HasController)
        {
            return;
        }

        // Think this is what I need to mod --> enabling BezierLocomotion<LineRenderer> && BezierLocomotion->inner_select->default
        // disabled by default, then enabled when button is pressed, comparable to:
        //if (OVRInput.Get(OVRInput.Button.One)){     //SecondaryIndexTrigger)) {
        //	laser.gameObject.SetActive (true);
        //	teleportAimerObject.SetActive (true);


        OVRInput.Controller controller = Controller;
        // change line below to change button mapping
        //bool currentTriggerState = OVRInput.Get (OVRInput.Button.PrimaryIndexTrigger, controller);
        bool currentTriggerState = OVRInput.Get(OVRInput.Button.PrimaryHandTrigger, controller);

        //bool currentTriggerState = OVRInput.Get (OVRInput.Button.One, controller);
        //bool currentTriggerState = (OVRInput.Get (OVRInput.Axis1D.PrimaryHandTrigger, controller) > 0.1f);

        if (currentTriggerState)
        {
            arcRenderer.enabled = true;
            arcLocation.gameObject.SetActive(true);
            //Debug.Log ("arc renderer should display");
        }
        else
        {
            arcRenderer.enabled = false;
            arcLocation.gameObject.SetActive(false);
        }

        // If the trigger was released this frame
        // comparable to OVRInput.GetUp
        if (lastTriggerState && !currentTriggerState)
        {
            Vector3 forward = objectToMove.forward;
            Vector3 up      = Vector3.up;

            // If there is a valid raycast
            if (arcRaycaster != null && arcRaycaster.MakingContact)
            {
                if (objectToMove != null)
                {
                    if (teleportedUpAxis == UpDirection.TargetNormal)
                    {
                        up = arcRaycaster.Normal;
                    }
                    objectToMove.position = arcRaycaster.HitPoint + up * height;
                }
            }

            if (OVRInput.Get(OVRInput.Touch.PrimaryTouchpad, controller) || OVRInput.Get(OVRInput.Touch.PrimaryThumbstick, controller))
            {
                forward = TouchpadDirection;
            }

            objectToMove.rotation = Quaternion.LookRotation(forward, up);
        }

        lastTriggerState = currentTriggerState;
    }
Esempio n. 28
0
 // Helper function to get the controller's world position
 private Vector3 getWorldPosition(OVRInput.Controller hand)
 {
     return(GetObjects.instance.getPlayer().gameObject.transform.parent.TransformPoint(OVRInput.GetLocalControllerPosition(hand)));
 }
Esempio n. 29
0
    void Update()
    {
        OVRInput.Controller activeController = OVRInput.GetActiveController();
        transform.localPosition = OVRInput.GetLocalControllerPosition(activeController);
        transform.localRotation = OVRInput.GetLocalControllerRotation(activeController);

        RaycastHit hitInfo2;

        if (Physics.Raycast(new Ray(transform.position, transform.forward), out hitInfo2))
        {
            if (hitInfo2.transform.tag == "Grabbable" && !isGrabbing)
            {
                if (hitTransform != null)
                {
                    SetHighlight(hitTransform, false);
                }

                hitTransform = hitInfo2.transform;
                SetHighlight(hitTransform, true);
            }
            else
            {
                if (hitTransform != null && !isGrabbing)
                {
                    SetHighlight(hitTransform, false);
                }
            }
        }
        else
        {
            if (hitTransform != null && !isGrabbing)
            {
                SetHighlight(hitTransform, false);
            }
        }

        if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger))
        {
            RaycastHit hitInfo;
            if (Physics.Raycast(new Ray(transform.position, transform.forward), out hitInfo))
            {
                if (hitInfo.transform.tag == "Grabbable")
                {
                    isGrabbing       = true;
                    grabbedTransform = hitInfo.transform;
                    grabbedTransform.GetComponent <Rigidbody>().isKinematic = true;
                    grabbedTransform.GetComponent <Rigidbody>().useGravity  = false;
                    grabbedTransform.parent = transform;
                }
            }
        }

        if (isGrabbing && OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger))
        {
            if (grabbedTransform != null)
            {
                grabbedTransform.GetComponent <Rigidbody>().isKinematic = false;
                grabbedTransform.GetComponent <Rigidbody>().useGravity  = true;
                grabbedTransform.parent = null;
            }
            isGrabbing = false;
        }

        /*if (isGrabbing && !OVRInput.Get(OVRInput.Button.One))
         * {
         *  float distance = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad).y;
         *
         *  grabbedTransform.position += distance * zSpeed * Time.deltaTime * transform.forward;
         *  grabbedTransform.localPosition = new Vector3(grabbedTransform.localPosition.x, grabbedTransform.localPosition.y, Mathf.Clamp(grabbedTransform.localPosition.z, 1.0f, 7.0f));
         * }*/
    }
Esempio n. 30
0
        // The following 2 functions are equivalent to PointerInputModule.GetMousePointerEventData but are customized to
        // get data for ray pointers and canvas mouse pointers.

        /// <summary>
        /// State for a pointer controlled by a world space ray. E.g. gaze pointer
        /// </summary>
        /// <returns></returns>
        virtual protected MouseState GetGazePointerData()
        {
            // Get the OVRRayPointerEventData reference
            OVRPointerEventData leftData;

            GetPointerData(kMouseLeftId, out leftData, true);
            leftData.Reset();

            //Now set the world space ray. This ray is what the user uses to point at UI elements
            // leftData.worldSpaceRay = new Ray(rayTransform.position, rayTransform.forward);
            //--------------------------------------------
            OVRInput.Controller controller = OVRInput.GetConnectedControllers() & (OVRInput.Controller.LTrackedRemote | OVRInput.Controller.RTrackedRemote);
            if (lineRenderer != null)
            {
                lineRenderer.enabled = trackingSpace != null && controller != OVRInput.Controller.None;
            }
            if (trackingSpace != null && controller != OVRInput.Controller.None)
            {
                controller = ((controller & OVRInput.Controller.LTrackedRemote) != OVRInput.Controller.None) ? OVRInput.Controller.LTrackedRemote : OVRInput.Controller.RTrackedRemote;

                Quaternion orientation     = OVRInput.GetLocalControllerRotation(controller);
                Vector3    localStartPoint = OVRInput.GetLocalControllerPosition(controller);

                Matrix4x4 localToWorld     = trackingSpace.localToWorldMatrix;
                Vector3   worldStartPoint  = localToWorld.MultiplyPoint(localStartPoint);
                Vector3   worldOrientation = localToWorld.MultiplyVector(orientation * Vector3.forward);
                leftData.worldSpaceRay = new Ray(worldStartPoint, worldOrientation);
                if (lineRenderer != null)
                {
                    lineRenderer.SetPosition(0, worldStartPoint);
                    lineRenderer.SetPosition(1, worldStartPoint + worldOrientation * 500.0f);
                }
            }
            else
            {
                leftData.worldSpaceRay = new Ray(rayTransform.position, rayTransform.forward);
            }
            //-------------------------------------
            leftData.scrollDelta = GetExtraScrollDelta();

            //Populate some default values
            leftData.button           = PointerEventData.InputButton.Left;
            leftData.useDragThreshold = true;
            // Perform raycast to find intersections with world
            eventSystem.RaycastAll(leftData, m_RaycastResultCache);
            var raycast = FindFirstRaycast(m_RaycastResultCache);

            leftData.pointerCurrentRaycast = raycast;
            m_RaycastResultCache.Clear();

            OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;

            // We're only interested in intersections from OVRRaycasters
            if (ovrRaycaster)
            {
                // The Unity UI system expects event data to have a screen position
                // so even though this raycast came from a world space ray we must get a screen
                // space position for the camera attached to this raycaster for compatability
                leftData.position = ovrRaycaster.GetScreenPosition(raycast);


                // Find the world position and normal the Graphic the ray intersected
                RectTransform graphicRect = raycast.gameObject.GetComponent <RectTransform>();
                if (graphicRect != null)
                {
                    // Set are gaze indicator with this world position and normal
                    Vector3 worldPos = raycast.worldPosition;
                    Vector3 normal   = GetRectTransformNormal(graphicRect);
                    OVRGazePointer.instance.SetPosition(worldPos, normal);
                    // Make sure it's being shown
                    OVRGazePointer.instance.RequestShow();
                }
            }

            // Now process physical raycast intersections
            OVRPhysicsRaycaster physicsRaycaster = raycast.module as OVRPhysicsRaycaster;

            if (physicsRaycaster)
            {
                Vector3 position = raycast.worldPosition;

                if (performSphereCastForGazepointer)
                {
                    // Here we cast a sphere into the scene rather than a ray. This gives a more accurate depth
                    // for positioning a circular gaze pointer
                    List <RaycastResult> results = new List <RaycastResult>();
                    physicsRaycaster.Spherecast(leftData, results, OVRGazePointer.instance.GetCurrentRadius());
                    if (results.Count > 0 && results[0].distance < raycast.distance)
                    {
                        position = results[0].worldPosition;
                    }
                }

                leftData.position = physicsRaycaster.GetScreenPos(raycast.worldPosition);

                // Show the cursor while pointing at an interactable object
                OVRGazePointer.instance.RequestShow();
                if (matchNormalOnPhysicsColliders)
                {
                    OVRGazePointer.instance.SetPosition(position, raycast.worldNormal);
                }
                else
                {
                    OVRGazePointer.instance.SetPosition(position);
                }
            }



            // Stick default data values in right and middle slots for compatability

            // copy the apropriate data into right and middle slots
            OVRPointerEventData rightData;

            GetPointerData(kMouseRightId, out rightData, true);
            CopyFromTo(leftData, rightData);
            rightData.button = PointerEventData.InputButton.Right;

            OVRPointerEventData middleData;

            GetPointerData(kMouseMiddleId, out middleData, true);
            CopyFromTo(leftData, middleData);
            middleData.button = PointerEventData.InputButton.Middle;


            m_MouseState.SetButtonState(PointerEventData.InputButton.Left, GetGazeButtonState(), leftData);
            m_MouseState.SetButtonState(PointerEventData.InputButton.Right, PointerEventData.FramePressState.NotChanged, rightData);
            m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, PointerEventData.FramePressState.NotChanged, middleData);
            return(m_MouseState);
        }