Esempio n. 1
0
    InputInfo FindInfoForDevice(SteamVR_Controller.Device dev)
    {
        for (int i = 0; i < _devices.Length; i++)
        {
            if (_devices[i].device == dev)
                return _devices[i];
        }

        return null;
    }
Esempio n. 2
0
 void FeedBack(SteamVR_Controller.Device device, int power, float duration)
 {
     this.UpdateAsObservable()
         .TakeUntil(Observable.Timer(TimeSpan.FromMilliseconds(duration)))
         .Subscribe(v =>
         {
             device.TriggerHapticPulse((ushort)power);
         }
         );
 }
    void DropItem(SteamVR_Controller.Device device)
    {
        if (itemInHand != null)
        {
            itemInHand.Dispatch(ObtainableItemEventType.OnDropOff, this);
            itemInHand.owner = null;

            itemInHand.GetComponent<Rigidbody>().velocity = device.velocity * 1.4f;

            itemInHand = null;
        }
    }
Esempio n. 4
0
    void Update()
    {
        if (controller == null || trackedController == null)
        {
            return;
        }

        device = SteamVR_Controller.Input((int)controller.index);
        // Touch down, possible chance for a swipe
        if ((int)controller.index != -1 && device.GetTouchDown(Valve.VR.EVRButtonId.k_EButton_Axis0))
        {
            trackingSwipe = true;
            // Record start time and position
            mStartPosition = new Vector2(device.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0).x,
                                         device.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0).y);
            mSwipeStartTime = Time.time;
        }
        // Touch up , possible chance for a swipe
        else if (device.GetTouchUp(Valve.VR.EVRButtonId.k_EButton_Axis0))
        {
            trackingSwipe = false;
            trackingSwipe = true;
            checkSwipe    = true;
        }
        else if (trackingSwipe)
        {
            endPosition = new Vector2(device.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0).x,
                                      device.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0).y);
        }

        if (checkSwipe)
        {
            checkSwipe = false;

            float   deltaTime   = Time.time - mSwipeStartTime;
            Vector2 swipeVector = endPosition - mStartPosition;

            float velocity = swipeVector.magnitude / deltaTime;
            if (velocity > mMinVelocity &&
                swipeVector.magnitude > mMinSwipeDist)
            {
                // if the swipe has enough velocity and enough distance
                swipeVector.Normalize();

                float angleOfSwipe = Vector2.Dot(swipeVector, mXAxis);
                angleOfSwipe = Mathf.Acos(angleOfSwipe) * Mathf.Rad2Deg;

                // Detect left and right swipe
                if (angleOfSwipe < mAngleRange)
                {
                    MenuEvents.ForEach(x =>
                    {
                        if (x.Active)
                        {
                            x.SwipeRight.Invoke();
                        }
                    });
                }
                else if ((180.0f - angleOfSwipe) < mAngleRange)
                {
                    MenuEvents.ForEach(x =>
                    {
                        if (x.Active)
                        {
                            x.SwipeLeft.Invoke();
                        }
                    });
                }
                else
                {
                    // Detect top and bottom swipe
                    angleOfSwipe = Vector2.Dot(swipeVector, mYAxis);
                    angleOfSwipe = Mathf.Acos(angleOfSwipe) * Mathf.Rad2Deg;
                    if (angleOfSwipe < mAngleRange)
                    {
                        MenuEvents.ForEach(x =>
                        {
                            if (x.Active)
                            {
                                x.SwipeUp.Invoke();
                            }
                        });
                    }
                    else if ((180.0f - angleOfSwipe) < mAngleRange)
                    {
                        MenuEvents.ForEach(x =>
                        {
                            if (x.Active)
                            {
                                x.SwipeDown.Invoke();
                            }
                        });
                    }
                }
            }
        }
        checkPadClicked();
    }
Esempio n. 5
0
    void Update()
    {
        // Device hot plugging support
        if (GetActiveChildCount(controllerManager.transform) != lastControllerAmount)
        {
            UpdateDeviceList();
        }
        lastControllerAmount = controllerManager.transform.childCount;

        // If no devices are connected or dashboard is open, wait for new devices
        if (devices.Count <= 0)
        {
            Debug.LogWarning("No devices!");
            return;
        }

        // Wait until user presses trigger to start
        if (!started)
        {
            for (int i = 0; i < devices.Count; ++i)
            {
                SteamVR_TrackedObject device = devices[i].GetComponent <SteamVR_TrackedObject>();

                if (device != null && device.index != SteamVR_TrackedObject.EIndex.Hmd)
                {
                    if (SteamVR_Controller.Input((int)device.index).GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger).x > 0.8f)
                    {
                        GetChannels(devices[i].position);
                        started = true;
                    }
                }
            }

            // Only run main code once we have started
            return;
        }

        // Find closest channels
        currentChannel = -1;
        float closestDistance = 99999f;

        for (int i = 0; i < channels.Count; ++i)
        {
            float dist = Vector3.Distance(channels[i].poses[0].pos, devices[channelController].position);
            if (dist < closestDistance)
            {
                closestDistance = dist;
                channelStrenght = dist;
                currentChannel  = i;
            }
        }

        // Switch and blend closest channels
        if (currentChannel != -1)
        {
            if (lastChannel != currentChannel)
            {
                compitingChannel = lastChannel;
                // Research this
                ChannelManager.e.SwitchChannels(ChannelManager.allChannels[currentChannel], ChannelManager.allChannels[compitingChannel]);
            }
            lastChannel = currentChannel;

            float blend = channelBlendCurve.Evaluate(channelStrenght);
            ChannelManager.e.SetChannelBlendValue(blend);

            Debug.DrawLine(channels[currentChannel].poses[0].pos, devices[channelController].position, Color.green);
            Debug.DrawLine(channels[compitingChannel].poses[0].pos, devices[channelController].position, Color.yellow);
        }

        // Update channel noise

        //pairs controllers with poses
        if (currentChannel >= 0)
        {
            float[] deviceNoises         = new float[devices.Count];
            float[] deviceRotationNoises = new float[devices.Count];

            globalMinDist = 999f;
            bestPairing   = new List <int>();

            recCompMin(new List <int>());


            //bestPairing.ForEach(dBug);
            for (int i = 1; i < devices.Count; ++i)
            {
                //reservedPoses.Add(i);
                //Debug.Log(i.ToString());
                //Debug.Log(bestPairing.Count.ToString());
                //Debug.Log(globalMinDist.ToString());
                Debug.DrawLine(channels[currentChannel].poses[i].pos, devices[bestPairing[i - 1]].position, Color.cyan);
                deviceNoises[i]         = Vector3.Distance(channels[currentChannel].poses[bestPairing[i - 1]].pos, devices[i].position);
                deviceRotationNoises[i] = Quaternion.Angle(channels[currentChannel].poses[bestPairing[i - 1]].rot, devices[i].rotation) / 180.0f;
            }


            // sets shader parameters and haptics
            for (int i = 1; i < 6; ++i)
            {
                tvParams.SetParameter(i - 1, 0.0f);
            }

            for (int i = 1; i < deviceNoises.Length; ++i)
            {
                float value = noiseCurve.Evaluate(deviceNoises[i]);
                value += rotationNoiseCurve.Evaluate(deviceRotationNoises[i]);

                Debug.Log(value);

                tvParams.SetParameter(i - 1, value);

                hapticsVal += Time.deltaTime * 10.0f;
                //if (hapticsVal > 1.0f)
                {
                    hapticsVal -= 1.0f;

                    ushort hapticsAmount = (ushort)(1800.0f * hapticsCurve.Evaluate(noiseCurve.Evaluate(deviceNoises[i])));

                    SteamVR_TrackedObject device = devices[i].GetComponent <SteamVR_TrackedObject>();

                    if (device != null && device.index != SteamVR_TrackedObject.EIndex.Hmd)
                    {
                        SteamVR_Controller.Input((int)device.index).TriggerHapticPulse(hapticsAmount, EVRButtonId.k_EButton_SteamVR_Touchpad);
                    }
                }
            }

            // Manage audio and UI
            if (AudioManager.instance != null)
            {
                float avarage    = 0.0f;
                float avarageRot = 0.0f;
                for (int i = 1; i < deviceNoises.Length; ++i)
                {
                    avarage    += deviceNoises[i];
                    avarageRot += deviceRotationNoises[i];
                }

                avarage    = avarage / (deviceNoises.Length - 1);
                avarageRot = avarageRot / (deviceNoises.Length - 1);
                avarage    = Mathf.Clamp01(avarage);
                avarageRot = Mathf.Clamp01(avarageRot);

                float connectionAmount = noiseCurve.Evaluate(avarage) + rotationNoiseCurve.Evaluate(avarageRot);
                connectionBar[0].SetActive(connectionAmount < 0.9f);
                connectionBar[1].SetActive(connectionAmount < 0.8f);
                connectionBar[2].SetActive(connectionAmount < 0.7f);
                connectionBar[3].SetActive(connectionAmount < 0.6f);
                connectionBar[4].SetActive(connectionAmount < 0.5f);
                connectionBar[5].SetActive(connectionAmount < 0.4f);
                connectionBar[6].SetActive(connectionAmount < 0.3f);
                connectionBar[7].SetActive(connectionAmount < 0.2f);
                connectionBar[8].SetActive(connectionAmount < 0.1f);
                connectionBar[9].SetActive(connectionAmount < 0.05f);

                AudioManager.instance.distortion = connectionAmount;
            }


            // Draw debug for channel points
            for (int i = 0; i < channels.Count; ++i)
            {
                if (i == this.currentChannel)
                {
                    for (int j = 0; j < devices.Count; ++j)
                    {
                        Debug.DrawLine(channels[i].poses[j].pos, RotatePointAroundPivot(channels[i].poses[j].pos + Vector3.up * 0.1f, channels[i].poses[j].pos, channels[i].poses[j].rot.eulerAngles), channels[i].debugColor);
                    }
                }
            }
        }
    }
Esempio n. 6
0
    private void GetHandleInput()
    {
        controllerIndex = (uint)trackedObj.index;
        device          = SteamVR_Controller.Input((int)trackedObj.index);

        Vector2 currentTriggerAxis  = device.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger);
        Vector2 currentTouchpadAxis = device.GetAxis();

        if (hapticPulseCountdown > 0)
        {
            device.TriggerHapticPulse(hapticPulseStrength);
            hapticPulseCountdown -= 1;
        }

        if (Vector2ShallowEquals(triggerAxis, currentTriggerAxis))
        {
            triggerAxisChanged = false;
        }
        else
        {
            OnTriggerAxisChanged(SetControllerEventArgs(ref triggerPressed, true, currentTriggerAxis.x));
            triggerAxisChanged = true;
        }


        if (Vector2ShallowEquals(touchpadAxis, currentTouchpadAxis))
        {
            touchpadAxisChanged = false;
        }
        else
        {
            OnTouchpadAxisChanged(SetControllerEventArgs(ref touchpadTouched, true, 1f));
            touchpadAxisChanged = true;
        }

        touchpadAxis = new Vector2(currentTouchpadAxis.x, currentTouchpadAxis.y);
        triggerAxis  = new Vector2(currentTriggerAxis.x, currentTriggerAxis.y);

        if (device.GetPressDown(SteamVR_Controller.ButtonMask.ApplicationMenu))
        {
            OnTriggerPressedDown(SetControllerEventArgs(ref triggerPressed, true, currentTouchpadAxis.x));
            triggerDown = true;
        }
        else
        {
            triggerDown = false;
        }

        if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
        {
            OnTriggerPressedUp(SetControllerEventArgs(ref triggerPressed, false, 0f));
            triggerUp = true;
        }
        else
        {
            triggerUp = false;
        }

        if (device.GetPressDown(SteamVR_Controller.ButtonMask.ApplicationMenu))
        {
            OnMenuPressedDown(SetControllerEventArgs(ref applicationMenuPressed, true, 1f));
        }

        if (device.GetPressUp(SteamVR_Controller.ButtonMask.ApplicationMenu))
        {
            OnMenuPressedUp(SetControllerEventArgs(ref applicationMenuPressed, false, 0f));
        }

        //Grip
        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Grip))
        {
            OnGripPressedDown(SetControllerEventArgs(ref gripPressed, true, 1f));
        }
        else if (device.GetPressUp(SteamVR_Controller.ButtonMask.Grip))
        {
            OnGripPressedUp(SetControllerEventArgs(ref gripPressed, false, 0f));
        }

        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
        {
            OnTouchpadPressedDown(SetControllerEventArgs(ref touchpadPressed, true, 1f));
        }
        else if (device.GetPressUp(SteamVR_Controller.ButtonMask.Touchpad))
        {
            OnTouchpadPressedUp(SetControllerEventArgs(ref touchpadPressed, false, 0f));
        }
    }
Esempio n. 7
0
    IEnumerator Start()
    {
        // We are a "no SteamVR fallback hand" if we have this camera set
        // we'll use the right mouse to look around and left mouse to interact
        // - don't need to find the device
        if (noSteamVRFallbackCamera)
        {
            yield break;
        }

        //Debug.Log( "VRHand - initializing connection routine" );

        // Acquire the correct device index for the hand we want to be
        // Also for the other hand if we get there first
        while (true)
        {
            // Don't need to run this every frame
            yield return(new WaitForSeconds(1.0f));

            // We have a controller now, break out of the loop!
            if (controller != null)
            {
                break;
            }

            //Debug.Log( "VRHand - checking controllers..." );

            // Initialize both hands simultaneously
            if (startingHandType == HandType.Left || startingHandType == HandType.Right)
            {
                // Left/right relationship.
                // Wait until we have a clear unique left-right relationship to initialize.
                int leftIndex  = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Leftmost);
                int rightIndex = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Rightmost);
                if (leftIndex == -1 || rightIndex == -1 || leftIndex == rightIndex)
                {
                    //Debug.Log( string.Format( "...Left/right hand relationship not yet established: leftIndex={0}, rightIndex={1}", leftIndex, rightIndex ) );
                    continue;
                }

                int myIndex    = (startingHandType == HandType.Right) ? rightIndex : leftIndex;
                int otherIndex = (startingHandType == HandType.Right) ? leftIndex : rightIndex;

                InitController(myIndex);
                if (otherHand)
                {
                    otherHand.InitController(otherIndex);
                }
            }
            else
            {
                // No left/right relationship. Just wait for a connection

                var vr = SteamVR.instance;
                for (int i = 0; i < Valve.VR.OpenVR.k_unMaxTrackedDeviceCount; i++)
                {
                    if (vr.hmd.GetTrackedDeviceClass((uint)i) != Valve.VR.ETrackedDeviceClass.Controller)
                    {
                        //Debug.Log( string.Format( "VRHand - device {0} is not a controller", i ) );
                        continue;
                    }

                    var device = SteamVR_Controller.Input(i);
                    if (!device.valid)
                    {
                        //Debug.Log( string.Format( "VRHand - device {0} is not valid", i ) );
                        continue;
                    }

                    if ((otherHand != null) && (otherHand.controller != null))
                    {
                        // Other hand is using this index, so we cannot use it.
                        if (i == (int)otherHand.controller.index)
                        {
                            //Debug.Log( string.Format( "VRHand - device {0} is owned by the other hand", i ) );
                            continue;
                        }
                    }

                    InitController(i);
                }
            }
        }
    }
Esempio n. 8
0
        void Update()
        {
            //if we don't have one of these, something is wrong, and we shouldn't do anything
            if (hmd == null || Left == null || Right == null)
            {
                return;
            }

            //If we have the left controller
            if (Left.isValid)
            {
                deviceLeft = SteamVR_Controller.Input((int)Left.index);

                VRInputDevice tempDevice = VRInput.GetDevice("ViveLeft");

                tempDevice.isTracked = true;
                tempDevice.SetInt("Index", (int)Left.index);
                tempDevice.transform = Left.transform;

                tempDevice.position        = Left.transform.position;
                tempDevice.forward         = Left.transform.forward;
                tempDevice.up              = Left.transform.up;
                tempDevice.right           = Left.transform.right;
                tempDevice.velocity        = deviceLeft.velocity;
                tempDevice.rotation        = Left.transform.rotation;
                tempDevice.angularVelocity = deviceLeft.angularVelocity;

                tempDevice.SetButton("Trigger", GetButtonInt(deviceLeft, EVRButtonId.k_EButton_SteamVR_Trigger));
                tempDevice.SetButton("Menu", GetButtonInt(deviceLeft, EVRButtonId.k_EButton_ApplicationMenu));
                tempDevice.SetButton("Touchpad", GetButtonInt(deviceLeft, EVRButtonId.k_EButton_SteamVR_Touchpad));
                tempDevice.SetButton("Grip", GetButtonInt(deviceLeft, EVRButtonId.k_EButton_Grip));

                tempDevice.SetTouchButton("Touchpad", GetTouchButtonInt(deviceLeft, EVRButtonId.k_EButton_SteamVR_Touchpad));

                Vector2 touchpadVector = deviceLeft.GetAxis(EVRButtonId.k_EButton_SteamVR_Touchpad);
                tempDevice.SetAxis("TouchpadX", touchpadVector.x);
                tempDevice.SetAxis("TouchpadY", touchpadVector.y);
                tempDevice.SetAxis("TouchpadR", Mathf.Sqrt(touchpadVector.x * touchpadVector.x + touchpadVector.y * touchpadVector.y));
                tempDevice.SetAxis("TouchpadT", Mathf.Atan2(touchpadVector.y, touchpadVector.x) * Mathf.Rad2Deg);
                tempDevice.SetAxis("Trigger", deviceLeft.GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger).x);

                tempDevice.Vibrate();

                /*
                 * ViveInput.Left.IsTracked = true;
                 * ViveInput.Left.Index = (int)Left.index;
                 * ViveInput.Left.Transform = Left.transform;
                 *
                 * ViveInput.Left.Position = Left.transform.position;//deviceLeft.transform.pos;
                 * ViveInput.Left.Forward = Left.transform.forward;
                 * ViveInput.Left.Up = Left.transform.up;
                 * ViveInput.Left.Right = Left.transform.right;
                 * ViveInput.Left.Velocity = deviceLeft.velocity;
                 * ViveInput.Left.Rotation = Left.transform.rotation;//deviceLeft.transform.rot;
                 * ViveInput.Left.AngularVelocity = deviceLeft.angularVelocity;
                 *
                 *
                 * ViveInput.Left.Buttons.Trigger = getButtonState(deviceLeft, EVRButtonId.k_EButton_SteamVR_Trigger);
                 * ViveInput.Left.TriggerAxis = deviceLeft.GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger);
                 * ViveInput.Left.Buttons.Grip = getButtonState(deviceLeft, EVRButtonId.k_EButton_Grip);
                 * ViveInput.Left.Buttons.TouchpadButton = getButtonState (deviceLeft, EVRButtonId.k_EButton_SteamVR_Touchpad);
                 * ViveInput.Left.Buttons.Menu = getButtonState (deviceLeft, EVRButtonId.k_EButton_ApplicationMenu);
                 *
                 * ViveInput.Left.TouchpadAxis = deviceLeft.GetAxis (EVRButtonId.k_EButton_SteamVR_Touchpad);
                 * if(ViveInput.Left.Buttons.TouchpadButton.Equals(ButtonState.Touched) || ViveInput.Left.Buttons.TouchpadButton.Equals(ButtonState.Pressed)) {
                 *      ViveInput.Left.TouchpadDeltaX = (ViveInput.Left.TouchpadAxis.x - lastLeftTouchpad.x) * Time.deltaTime;
                 *      ViveInput.Left.TouchpadDeltaY = (ViveInput.Left.TouchpadAxis.y - lastLeftTouchpad.y) * Time.deltaTime;
                 *      ViveInput.Left.TouchpadDeltaR = ((ViveInput.Left.TouchpadAxis).magnitude - (lastLeftTouchpad).magnitude) * Time.deltaTime;
                 *      ViveInput.Left.TouchpadDeltaT = getDeltaAngle(ViveInput.Left.TouchpadAxis, lastLeftTouchpad) * Time.deltaTime;
                 * } else {
                 *      ViveInput.Left.TouchpadDeltaX = ViveInput.Left.TouchpadDeltaY = ViveInput.Left.TouchpadDeltaR = ViveInput.Left.TouchpadDeltaT = 0f;
                 * }
                 * ViveInput.Left.TouchpadDir = getTouchpadDir(ViveInput.Left.TouchpadAxis, ViveInput.Left.Buttons.TouchpadButton);
                 *
                 * lastLeftTouchpad = ViveInput.Left.TouchpadAxis;
                 */
            }
            else
            {
                VRInput.GetDevice("ViveLeft").isTracked = false;
                deviceLeft = null;
                //deviceLeft = null;
                //ViveInput.Left.IsTracked = false;
            }
            //If we have the right controller
            if (Right.isValid)
            {
                deviceRight = SteamVR_Controller.Input((int)Right.index);

                VRInputDevice tempDevice = VRInput.GetDevice("ViveRight");

                tempDevice.isTracked = true;
                tempDevice.SetInt("Index", (int)Right.index);
                tempDevice.transform = Right.transform;

                tempDevice.position        = Right.transform.position;
                tempDevice.forward         = Right.transform.forward;
                tempDevice.up              = Right.transform.up;
                tempDevice.right           = Right.transform.right;
                tempDevice.velocity        = deviceRight.velocity;
                tempDevice.rotation        = Right.transform.rotation;
                tempDevice.angularVelocity = deviceRight.angularVelocity;

                tempDevice.SetButton("Trigger", GetButtonInt(deviceRight, EVRButtonId.k_EButton_SteamVR_Trigger));
                tempDevice.SetButton("Menu", GetButtonInt(deviceRight, EVRButtonId.k_EButton_ApplicationMenu));
                tempDevice.SetButton("Touchpad", GetButtonInt(deviceRight, EVRButtonId.k_EButton_SteamVR_Touchpad));
                tempDevice.SetButton("Grip", GetButtonInt(deviceRight, EVRButtonId.k_EButton_Grip));

                tempDevice.SetTouchButton("Touchpad", GetTouchButtonInt(deviceRight, EVRButtonId.k_EButton_SteamVR_Touchpad));

                Vector2 touchpadVector = deviceRight.GetAxis(EVRButtonId.k_EButton_SteamVR_Touchpad);
                tempDevice.SetAxis("TouchpadX", touchpadVector.x);
                tempDevice.SetAxis("TouchpadY", touchpadVector.y);
                tempDevice.SetAxis("TouchpadR", Mathf.Sqrt(touchpadVector.x * touchpadVector.x + touchpadVector.y * touchpadVector.y));
                tempDevice.SetAxis("TouchpadT", Mathf.Atan2(touchpadVector.y, touchpadVector.x) * Mathf.Rad2Deg);
                tempDevice.SetAxis("Trigger", deviceRight.GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger).x);

                tempDevice.Vibrate();

                /*
                 * ViveInput.Right.IsTracked = true;
                 * ViveInput.Right.Index = (int)Right.index;
                 * ViveInput.Right.Transform = Right.transform;
                 *
                 * ViveInput.Right.Position = Right.transform.position;//deviceRight.transform.pos;
                 * ViveInput.Right.Forward = Right.transform.forward;
                 * ViveInput.Right.Up = Right.transform.up;
                 * ViveInput.Right.Right = Right.transform.right;
                 * ViveInput.Right.Velocity = deviceRight.velocity;
                 * ViveInput.Right.Rotation = Right.transform.rotation;//deviceRight.transform.rot;
                 * ViveInput.Right.AngularVelocity = deviceRight.angularVelocity;
                 *
                 * ViveInput.Right.Buttons.Trigger = getButtonState(deviceRight, EVRButtonId.k_EButton_SteamVR_Trigger);
                 * ViveInput.Right.TriggerAxis = deviceRight.GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger);
                 * ViveInput.Right.Buttons.Grip = getButtonState(deviceRight, EVRButtonId.k_EButton_Grip);
                 * ViveInput.Right.Buttons.TouchpadButton = getButtonState (deviceRight, EVRButtonId.k_EButton_SteamVR_Touchpad);
                 * ViveInput.Right.Buttons.Menu = getButtonState (deviceRight, EVRButtonId.k_EButton_ApplicationMenu);
                 *
                 * ViveInput.Right.TouchpadAxis = deviceRight.GetAxis (EVRButtonId.k_EButton_SteamVR_Touchpad);
                 * if(ViveInput.Right.Buttons.TouchpadButton.Equals(ButtonState.Touched) || ViveInput.Right.Buttons.TouchpadButton.Equals(ButtonState.Pressed)) {
                 *      ViveInput.Right.TouchpadDeltaX = (ViveInput.Right.TouchpadAxis.x - lastRightTouchpad.x) * Time.deltaTime;
                 *      ViveInput.Right.TouchpadDeltaY = (ViveInput.Right.TouchpadAxis.y - lastRightTouchpad.y) * Time.deltaTime;
                 *      ViveInput.Right.TouchpadDeltaR = ((ViveInput.Right.TouchpadAxis).magnitude - (lastRightTouchpad).magnitude) * Time.deltaTime;
                 *      ViveInput.Right.TouchpadDeltaT = getDeltaAngle(ViveInput.Right.TouchpadAxis, lastRightTouchpad) * Time.deltaTime;
                 * } else {
                 *      ViveInput.Right.TouchpadDeltaX = ViveInput.Right.TouchpadDeltaY = ViveInput.Right.TouchpadDeltaR = ViveInput.Right.TouchpadDeltaT = 0f;
                 * }
                 * ViveInput.Right.TouchpadDir = getTouchpadDir(ViveInput.Right.TouchpadAxis, ViveInput.Right.Buttons.TouchpadButton);
                 *
                 * lastRightTouchpad = ViveInput.Right.TouchpadAxis;
                 */
            }
            else
            {
                VRInput.GetDevice("ViveRight").isTracked = false;
                deviceRight = null;
                //ViveInput.Right.IsTracked = false;
            }
                        #if UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4
            //If we have the HMD
            if (hmd.isValid)
            {
                deviceHMD = SteamVR_Controller.Input((int)hmd.index);

                VRInputDevice tempDevice = VRInput.GetDevice("ViveHMD");

                tempDevice.isTracked = true;
                tempDevice.SetInt("Index", (int)hmd.index);
                tempDevice.transform = hmd.transform;

                tempDevice.position        = hmd.transform.position;
                tempDevice.forward         = hmd.transform.forward;
                tempDevice.up              = hmd.transform.up;
                tempDevice.right           = hmd.transform.right;
                tempDevice.velocity        = deviceHMD.velocity;
                tempDevice.rotation        = hmd.transform.rotation;
                tempDevice.angularVelocity = deviceHMD.angularVelocity;

                /*
                 * ViveInput.HMD.IsTracked = true;
                 * ViveInput.HMD.Index = (int)hmd.index;
                 * ViveInput.HMD.Transform = hmd.transform;
                 *
                 * ViveInput.HMD.Position = hmd.transform.position;
                 * ViveInput.HMD.Forward = hmd.transform.forward;
                 * ViveInput.HMD.Up = hmd.transform.up;
                 * ViveInput.HMD.Right = hmd.transform.right;
                 * ViveInput.HMD.Velocity = deviceHMD.velocity;
                 * ViveInput.HMD.Rotation = deviceHMD.transform.rot;
                 * ViveInput.HMD.AngularVelocity = deviceHMD.angularVelocity;
                 *
                 * ViveInput.HMD.Buttons.Trigger = ButtonState.Inactive;
                 * ViveInput.HMD.Buttons.Grip = ButtonState.Inactive;
                 * ViveInput.HMD.Buttons.TouchpadButton = ButtonState.Inactive;
                 * ViveInput.HMD.Buttons.Menu = ButtonState.Inactive;
                 *
                 * ViveInput.HMD.TouchpadAxis = Vector3.zero;
                 */
            }
            else
            {
                VRInput.GetDevice("ViveHMD").isTracked = false;
                deviceHMD = null;
                //ViveInput.HMD.IsTracked = false;
            }
                        #else
            if (VRDevice.isPresent)
            {
                VRInputDevice tempDevice = VRInput.GetDevice("ViveHMD");

                tempDevice.isTracked = true;
                tempDevice.transform = hmd;

                tempDevice.position = hmd.position;
                tempDevice.forward  = hmd.forward;
                tempDevice.up       = hmd.up;
                tempDevice.right    = hmd.right;
                tempDevice.rotation = hmd.transform.rotation;

                tempDevice.velocity        = (hmd.position - lastPosition) / Time.deltaTime;
                tempDevice.angularVelocity = (hmd.rotation * Quaternion.Inverse(lastRotation)).eulerAngles / Time.deltaTime;

                lastPosition = hmd.position;
                lastRotation = hmd.rotation;

                tempDevice.SetString("Model", VRDevice.model);
                tempDevice.SetFloat("RefreshRate", VRDevice.refreshRate);

                tempDevice.SetVector3("Head", InputTracking.GetLocalPosition(VRNode.Head));
                tempDevice.SetVector3("LeftEye", InputTracking.GetLocalPosition(VRNode.LeftEye));
                tempDevice.SetVector3("RightEye", InputTracking.GetLocalPosition(VRNode.RightEye));
                tempDevice.SetVector3("CenterEye", InputTracking.GetLocalPosition(VRNode.CenterEye));

                tempDevice.SetQuaternion("Head", InputTracking.GetLocalRotation(VRNode.Head));
                tempDevice.SetQuaternion("LeftEye", InputTracking.GetLocalRotation(VRNode.LeftEye));
                tempDevice.SetQuaternion("RightEye", InputTracking.GetLocalRotation(VRNode.RightEye));
                tempDevice.SetQuaternion("CenterEye", InputTracking.GetLocalRotation(VRNode.CenterEye));
            }
            else
            {
                VRInput.GetDevice("ViveHMD").isTracked = false;
            }
                        #endif
        }
Esempio n. 9
0
    void Update()
    {
        controllerIndex = (uint)trackedController.index;
        device          = SteamVR_Controller.Input((int)controllerIndex);

        Vector2 currentTriggerAxis  = device.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger);
        Vector2 currentTouchpadAxis = device.GetAxis();

        if (Vector2ShallowEquals(triggerAxis, currentTriggerAxis))
        {
            triggerAxisChanged = false;
        }
        else
        {
            OnTriggerAxisChanged(SetButtonEvent(ref triggerAxisChanged, true, currentTriggerAxis.x));
        }

        if (Vector2ShallowEquals(touchpadAxis, currentTouchpadAxis))
        {
            touchpadAxisChanged = false;
        }
        else
        {
            OnTouchpadAxisChanged(SetButtonEvent(ref touchpadTouched, true, 1f));
            touchpadAxisChanged = true;
        }

        touchpadAxis = new Vector2(currentTouchpadAxis.x, currentTouchpadAxis.y);
        triggerAxis  = new Vector2(currentTriggerAxis.x, currentTriggerAxis.y);

        //Trigger
        if (device.GetTouchDown(SteamVR_Controller.ButtonMask.Trigger))
        {
            OnTriggerClicked(SetButtonEvent(ref triggerPressed, true, currentTriggerAxis.x));
            EmitAlias(ButtonAlias.Trigger, true, currentTriggerAxis.x, ref triggerPressed);
        }
        else if (device.GetTouchUp(SteamVR_Controller.ButtonMask.Trigger))
        {
            OnTriggerUnclicked(SetButtonEvent(ref triggerPressed, false, 0f));
            EmitAlias(ButtonAlias.Trigger, false, 0f, ref triggerPressed);
        }

        //ApplicationMenu
        if (device.GetTouchDown(SteamVR_Controller.ButtonMask.ApplicationMenu))
        {
            OnApplicationMenuClicked(SetButtonEvent(ref applicationMenuPressed, true, 1f));
            EmitAlias(ButtonAlias.Application_Menu, true, 1f, ref applicationMenuPressed);
        }
        else if (device.GetTouchUp(SteamVR_Controller.ButtonMask.ApplicationMenu))
        {
            OnApplicationMenuUnclicked(SetButtonEvent(ref applicationMenuPressed, false, 0f));
            EmitAlias(ButtonAlias.Application_Menu, false, 0f, ref applicationMenuPressed);
        }

        //Grip
        if (device.GetTouchDown(SteamVR_Controller.ButtonMask.Grip))
        {
            OnGripClicked(SetButtonEvent(ref gripPressed, true, 1f));
            EmitAlias(ButtonAlias.Grip, true, 1f, ref gripPressed);
        }
        else if (device.GetTouchUp(SteamVR_Controller.ButtonMask.Grip))
        {
            OnGripUnclicked(SetButtonEvent(ref gripPressed, false, 0f));
            EmitAlias(ButtonAlias.Grip, false, 0f, ref gripPressed);
        }

        //Touchpad Clicked
        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
        {
            OnTouchpadClicked(SetButtonEvent(ref touchpadPressed, true, 1f));
            EmitAlias(ButtonAlias.Touchpad_Press, true, 1f, ref touchpadPressed);
        }
        else if (device.GetPressUp(SteamVR_Controller.ButtonMask.Touchpad))
        {
            OnTouchpadUnclicked(SetButtonEvent(ref touchpadPressed, false, 0f));
            EmitAlias(ButtonAlias.Touchpad_Press, false, 0f, ref touchpadPressed);
        }

        //Touchpad Touched
        if (device.GetTouchDown(SteamVR_Controller.ButtonMask.Touchpad))
        {
            OnTouchpadTouched(SetButtonEvent(ref touchpadTouched, true, 1f));
            EmitAlias(ButtonAlias.Touchpad_Touch, true, 1f, ref touchpadTouched);
        }
        else if (device.GetTouchUp(SteamVR_Controller.ButtonMask.Touchpad))
        {
            OnTouchpadUntouched(SetButtonEvent(ref touchpadTouched, false, 0f));
            EmitAlias(ButtonAlias.Touchpad_Touch, false, 0f, ref touchpadTouched);
        }
    }
Esempio n. 10
0
    // Corourtine to handle all the steps across loading boundaries.
    IEnumerator LoadLevel()
    {
        // Optionally rotate loading screen transform around the camera into view.
        // We assume here that the loading screen is already facing toward the origin,
        // and that the progress bar transform (if any) is a child and will follow along.
        if (loadingScreen != null && loadingScreenDistance > 0.0f)
        {
            // Wait until we have tracking.
            var hmd = SteamVR_Controller.Input((int)OpenVR.k_unTrackedDeviceIndex_Hmd);
            while (!hmd.hasTracking)
            {
                yield return(null);
            }

            var tloading = hmd.transform;
            tloading.rot  = Quaternion.Euler(0.0f, tloading.rot.eulerAngles.y, 0.0f);
            tloading.pos += tloading.rot * new Vector3(0.0f, 0.0f, loadingScreenDistance);

            var t = loadingScreenTransform != null ? loadingScreenTransform : transform;
            t.position = tloading.pos;
            t.rotation = tloading.rot;
        }

        _active = this;

        SteamVR_Events.Loading.Send(true);

        // Calculate rate for fading in loading screen and progress bar.
        if (loadingScreenFadeInTime > 0.0f)
        {
            fadeRate = 1.0f / loadingScreenFadeInTime;
        }
        else
        {
            alpha = 1.0f;
        }

        var overlay = OpenVR.Overlay;

        // Optionally create our loading screen overlay.
        if (loadingScreen != null && overlay != null)
        {
            loadingScreenOverlayHandle = GetOverlayHandle("loadingScreen", loadingScreenTransform != null ? loadingScreenTransform : transform, loadingScreenWidthInMeters);
            if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
            {
                var texture = new Texture_t();
                texture.handle      = loadingScreen.GetNativeTexturePtr();
                texture.eType       = SteamVR.instance.textureType;
                texture.eColorSpace = EColorSpace.Auto;
                overlay.SetOverlayTexture(loadingScreenOverlayHandle, ref texture);
            }
        }

        bool fadedForeground = false;

        // Fade out to compositor
        SteamVR_Events.LoadingFadeOut.Send(fadeOutTime);

        // Optionally set a skybox to use as a backdrop in the compositor.
        var compositor = OpenVR.Compositor;

        if (compositor != null)
        {
            if (front != null)
            {
                SteamVR_Skybox.SetOverride(front, back, left, right, top, bottom);

                // Explicitly fade to the compositor since loading will cause us to stop rendering.
                compositor.FadeGrid(fadeOutTime, true);
                yield return(new WaitForSeconds(fadeOutTime));
            }
            else if (backgroundColor != Color.clear)
            {
                // Otherwise, use the specified background color.
                if (showGrid)
                {
                    // Set compositor background color immediately, and start fading to it.
                    compositor.FadeToColor(0.0f, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, true);
                    compositor.FadeGrid(fadeOutTime, true);
                    yield return(new WaitForSeconds(fadeOutTime));
                }
                else
                {
                    // Fade the foreground color in (which will blend on top of the scene), and then cut to the compositor.
                    compositor.FadeToColor(fadeOutTime, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, false);
                    yield return(new WaitForSeconds(fadeOutTime + 0.1f));

                    compositor.FadeGrid(0.0f, true);
                    fadedForeground = true;
                }
            }
        }

        // Now that we're fully faded out, we can stop submitting frames to the compositor.
        SteamVR_Render.pauseRendering = true;

        // Continue waiting for the overlays to fully fade in before continuing.
        while (alpha < 1.0f)
        {
            yield return(null);
        }

        // Keep us from getting destroyed when loading the new level, otherwise this coroutine will get stopped prematurely.
        transform.parent = null;
        DontDestroyOnLoad(gameObject);

        if (!string.IsNullOrEmpty(internalProcessPath))
        {
            Debug.Log("Launching external application...");
            var applications = OpenVR.Applications;
            if (applications == null)
            {
                Debug.Log("Failed to get OpenVR.Applications interface!");
            }
            else
            {
                var workingDirectory = Directory.GetCurrentDirectory();
                var fullPath         = Path.Combine(workingDirectory, internalProcessPath);
                Debug.Log("LaunchingInternalProcess");
                Debug.Log("ExternalAppPath = " + internalProcessPath);
                Debug.Log("FullPath = " + fullPath);
                Debug.Log("ExternalAppArgs = " + internalProcessArgs);
                Debug.Log("WorkingDirectory = " + workingDirectory);
                var error = applications.LaunchInternalProcess(fullPath, internalProcessArgs, workingDirectory);
                Debug.Log("LaunchInternalProcessError: " + error);
#if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
#elif !UNITY_METRO
                System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
            }
        }
        else
        {
            var mode = loadAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single;
            if (loadAsync)
            {
                Application.backgroundLoadingPriority = ThreadPriority.Low;
                async = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(levelName, mode);

                // Performing this in a while loop instead seems to help smooth things out.
                //yield return async;
                while (!async.isDone)
                {
                    yield return(null);
                }
            }
            else
            {
                UnityEngine.SceneManagement.SceneManager.LoadScene(levelName, mode);
            }
        }

        yield return(null);

        System.GC.Collect();

        yield return(null);

        Shader.WarmupAllShaders();

        // Optionally wait a short period of time after loading everything back in, but before we start rendering again
        // in order to give everything a change to settle down to avoid any hitching at the start of the new level.
        yield return(new WaitForSeconds(postLoadSettleTime));

        SteamVR_Render.pauseRendering = false;

        // Fade out loading screen.
        if (loadingScreenFadeOutTime > 0.0f)
        {
            fadeRate = -1.0f / loadingScreenFadeOutTime;
        }
        else
        {
            alpha = 0.0f;
        }

        // Fade out to compositor
        SteamVR_Events.LoadingFadeIn.Send(fadeInTime);

        // Refresh compositor reference since loading scenes might have invalidated it.
        compositor = OpenVR.Compositor;
        if (compositor != null)
        {
            // Fade out foreground color if necessary.
            if (fadedForeground)
            {
                compositor.FadeGrid(0.0f, false);
                compositor.FadeToColor(fadeInTime, 0.0f, 0.0f, 0.0f, 0.0f, false);
                yield return(new WaitForSeconds(fadeInTime));
            }
            else
            {
                // Fade scene back in, and reset skybox once no longer visible.
                compositor.FadeGrid(fadeInTime, false);
                yield return(new WaitForSeconds(fadeInTime));

                if (front != null)
                {
                    SteamVR_Skybox.ClearOverride();
                }
            }
        }

        // Finally, stick around long enough for our overlays to fully fade out.
        while (alpha > 0.0f)
        {
            yield return(null);
        }

        if (overlay != null)
        {
            if (progressBarOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
            {
                overlay.HideOverlay(progressBarOverlayHandle);
            }
            if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
            {
                overlay.HideOverlay(loadingScreenOverlayHandle);
            }
        }

        Destroy(gameObject);

        _active = null;

        SteamVR_Events.Loading.Send(false);
    }
Esempio n. 11
0
 void Start()
 {
     m_trackedObj = GetComponent <SteamVR_TrackedObject>();
     m_deivce     = SteamVR_Controller.Input((int)m_trackedObj.index);
 }
Esempio n. 12
0
 public override void OnExitControl(GameObject control)
 {
     var device = SteamVR_Controller.Input(_index);
     //device.TriggerHapticPulse(600);
 }
Esempio n. 13
0
    void FixedUpdate()
    {
        head.position = hmd.position;
        head.rotation = hmd.rotation;
        leftHand.transform.position  = leftController.position;
        rightHand.transform.position = rightController.position;
        leftHand.transform.rotation  = leftController.rotation;
        rightHand.transform.rotation = rightController.rotation;

        int leftIndex = (int)leftController.GetComponent <SteamVR_TrackedObject>().index;

        if (leftIndex >= 0)
        {
            float leftTrigger = SteamVR_Controller.Input(leftIndex).GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger).magnitude;
            if (leftHand.intersected != null && leftTrigger > 0.2f)
            {
                leftHeldObject = leftHand.intersected;
                saveMaxLeft    = leftHand.intersected.maxAngularVelocity;
                leftHand.intersected.maxAngularVelocity = Mathf.Infinity;
            }
            if (leftHeldObject != null && leftTrigger <= 0.2f)
            {
                //release it
                leftHeldObject.isKinematic = false;

                leftHeldObject.velocity           = SteamVR_Controller.Input(leftIndex).velocity;
                leftHeldObject.angularVelocity    = SteamVR_Controller.Input(leftIndex).angularVelocity;
                leftHeldObject.maxAngularVelocity = saveMaxLeft;
                leftHeldObject = null;
            }
            if (leftHeldObject != null)
            {
                //force the object to follow my hand (isKinematic == true)
                leftHeldObject.isKinematic = true;

                leftHeldObject.position = leftHand.transform.position;
                leftHeldObject.rotation = leftHand.transform.rotation;

                //force the object to follow my hand (isKinematic == false)
                //leftHeldObject.velocity = (leftHand.transform.position - leftHeldObject.position) / Time.deltaTime;
                //float angle;
                //Vector3 axis;
                //Quaternion q = leftHand.transform.rotation * Quaternion.Inverse(leftHeldObject.rotation);
                //q.ToAngleAxis(out angle, out axis);

                //leftHeldObject.angularVelocity = axis * angle * Mathf.Deg2Rad / Time.deltaTime;
            }
        }
        int rightIndex = (int)rightController.GetComponent <SteamVR_TrackedObject>().index;

        if (rightIndex >= 0)
        {
            float rightTrigger = SteamVR_Controller.Input(rightIndex).GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger).magnitude;
            if (rightHand.intersected != null && rightTrigger > 0.2f)
            {
                rightHeldObject = rightHand.intersected;
                saveMaxRight    = rightHand.intersected.maxAngularVelocity;
                rightHand.intersected.maxAngularVelocity = Mathf.Infinity;
            }

            if (rightHeldObject != null && rightTrigger <= 0.2f)
            {
                //release it
                rightHeldObject.isKinematic = false;

                rightHeldObject.velocity           = SteamVR_Controller.Input(rightIndex).velocity;
                rightHeldObject.angularVelocity    = SteamVR_Controller.Input(rightIndex).angularVelocity;
                rightHeldObject.maxAngularVelocity = saveMaxRight;
                rightHeldObject = null;
            }

            if (rightHeldObject != null)
            {
                //force the object to follow my hand (isKinematic == true)
                rightHeldObject.isKinematic = true;

                rightHeldObject.position = rightHand.transform.position;
                rightHeldObject.rotation = rightHand.transform.rotation;

                //force the object to follow my hand (isKinematic == false)
                //rightHeldObject.velocity = (rightHand.transform.position - rightHeldObject.position) / Time.deltaTime;
                //float angle;
                //Vector3 axis;
                //Quaternion q = rightHand.transform.rotation * Quaternion.Inverse(rightHeldObject.rotation);
                //q.ToAngleAxis(out angle, out axis);

                //rightHeldObject.angularVelocity = axis * angle * Mathf.Deg2Rad / Time.deltaTime;
            }
        }
    }
    void Update()
    {
        // Force controller update in case no one else called this frame to ensure prevState gets updated.
        SteamVR_Controller.Update();

        // Dispatch any OpenVR events.
        var system = OpenVR.System;

        if (system != null)
        {
            var vrEvent = new VREvent_t();
            var size    = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VREvent_t));
            for (int i = 0; i < 64; i++)
            {
                if (!system.PollNextEvent(ref vrEvent, size))
                {
                    break;
                }

                switch ((EVREventType)vrEvent.eventType)
                {
                case EVREventType.VREvent_InputFocusCaptured:                         // another app has taken focus (likely dashboard)
                    if (vrEvent.data.process.oldPid == 0)
                    {
                        SteamVR_Events.InputFocus.Send(false);
                    }
                    break;

                case EVREventType.VREvent_InputFocusReleased:                         // that app has released input focus
                    if (vrEvent.data.process.pid == 0)
                    {
                        SteamVR_Events.InputFocus.Send(true);
                    }
                    break;

                case EVREventType.VREvent_ShowRenderModels:
                    SteamVR_Events.HideRenderModels.Send(false);
                    break;

                case EVREventType.VREvent_HideRenderModels:
                    SteamVR_Events.HideRenderModels.Send(true);
                    break;

                default:
                    SteamVR_Events.System((EVREventType)vrEvent.eventType).Send(vrEvent);
                    break;
                }
            }
        }

        // Ensure various settings to minimize latency.
        Application.targetFrameRate     = -1;
        Application.runInBackground     = true; // don't require companion window focus
        QualitySettings.maxQueuedFrames = -1;
        QualitySettings.vSyncCount      = 0;    // this applies to the companion window

        if (lockPhysicsUpdateRateToRenderFrequency && Time.timeScale > 0.0f)
        {
            var vr = SteamVR.instance;
            if (vr != null)
            {
                var timing = new Compositor_FrameTiming();
                timing.m_nSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Compositor_FrameTiming));
                vr.compositor.GetFrameTiming(ref timing, 0);

                Time.fixedDeltaTime = Time.timeScale / vr.hmd_DisplayFrequency;
            }
        }
    }
Esempio n. 15
0
 void FixedUpdate()
 {
     device = SteamVR_Controller.Input((int)paddle.index);
 }
    void Update()

    {
        if (Dreapta)
        {
            isright = false;
            if (isleft)
            {
                // If we are currently teleporting (ie handling the fade in/out transition)...
                if (CurrentTeleportState == TeleportState.Teleporting)
                {
                    // Wait until half of the teleport time has passed before the next event (note: both the switch from fade
                    // out to fade in and the switch from fade in to stop the animation is half of the fade duration)
                    if (Time.time - TeleportTimeMarker >= TeleportFadeDuration / 2)
                    {
                        if (FadingIn)
                        {
                            // We have finished fading in
                            CurrentTeleportState = TeleportState.None;
                        }
                        else
                        {
                            // We have finished fading out - time to teleport!
                            Vector3 offset = OriginTransform.position - HeadTransform.position;
                            offset.y = 0;
                            OriginTransform.position = Pointer.SelectedPoint + offset;
                        }

                        TeleportTimeMarker = Time.time;
                        FadingIn           = !FadingIn;
                    }
                }
                // At this point, we are NOT actively teleporting.  So now we care about controller input.
                else if (CurrentTeleportState == TeleportState.Selecting)
                {
                    Debug.Assert(ActiveController != null);

                    // Here, there is an active controller - that is, the user is holding down on the trackpad.
                    // Poll controller for pertinent button data
                    int  index          = (int)ActiveController.index;
                    var  device         = SteamVR_Controller.Input(index);
                    bool shouldTeleport = device.GetPressUp(SteamVR_Controller.ButtonMask.Touchpad);
                    bool shouldCancel   = device.GetPressUp(SteamVR_Controller.ButtonMask.Grip);
                    if (shouldTeleport || shouldCancel)
                    {
                        // If the user has decided to teleport (ie lets go of touchpad) then remove all visual indicators
                        // related to selecting things and actually teleport
                        // If the user has decided to cancel (ie squeezes grip button) then remove visual indicators and do nothing
                        if (shouldTeleport && Pointer.PointOnNavMesh)
                        {
                            // Begin teleport sequence
                            CurrentTeleportState = TeleportState.Teleporting;
                            TeleportTimeMarker   = Time.time;
                        }
                        else
                        {
                            CurrentTeleportState = TeleportState.None;
                        }

                        // Reset active controller, disable pointer, disable visual indicators
                        ActiveController   = null;
                        Pointer.enabled    = false;
                        RoomBorder.enabled = false;
                        //RoomBorder.Transpose = Matrix4x4.TRS(OriginTransform.position, Quaternion.identity, Vector3.one);
                        if (NavmeshAnimator != null)
                        {
                            NavmeshAnimator.SetBool(EnabledAnimatorID, false);
                        }

                        Pointer.transform.parent     = null;
                        Pointer.transform.position   = Vector3.zero;
                        Pointer.transform.rotation   = Quaternion.identity;
                        Pointer.transform.localScale = Vector3.one;
                    }
                    else
                    {
                        // The user is still deciding where to teleport and has the touchpad held down.
                        // Note: rendering of the parabolic pointer / marker is done in ParabolicPointer
                        Vector3 offset = HeadTransform.position - OriginTransform.position;
                        offset.y = 0;

                        // Render representation of where the chaperone bounds will be after teleporting
                        RoomBorder.enabled   = Pointer.PointOnNavMesh;
                        RoomBorder.Transpose = Matrix4x4.TRS(Pointer.SelectedPoint - offset, Quaternion.identity, Vector3.one);

                        // Haptic feedback click every [HaptickClickAngleStep] degrees
                        if (Pointer.CurrentParabolaAngleY >= 45) // Don't click when at max degrees
                        {
                            LastClickAngle = Pointer.CurrentPointVector;
                        }

                        float angleClickDiff = Vector3.Angle(LastClickAngle, Pointer.CurrentPointVector);
                        if (IsClicking && Mathf.Abs(angleClickDiff) > HapticClickAngleStep)
                        {
                            LastClickAngle = Pointer.CurrentPointVector;
                            if (Pointer.PointOnNavMesh)
                            {
                                device.TriggerHapticPulse();
                            }
                        }

                        // Trigger a stronger haptic pulse when "entering" a teleportable surface
                        if (Pointer.PointOnNavMesh && !IsClicking)
                        {
                            IsClicking = true;
                            device.TriggerHapticPulse(750);
                            LastClickAngle = Pointer.CurrentPointVector;
                        }
                        else if (!Pointer.PointOnNavMesh && IsClicking)
                        {
                            IsClicking = false;
                        }
                    }
                }
                else //CurrentTeleportState == TeleportState.None
                {
                    // At this point the user is not holding down on the touchpad at all or has canceled a teleport and hasn't
                    // let go of the touchpad.  So we wait for the user to press the touchpad and enable visual indicators
                    // if necessary.
                    foreach (SteamVR_TrackedObject obj in Controllers)
                    {
                        int index = (int)obj.index;
                        if (index == -1)
                        {
                            continue;
                        }

                        var device = SteamVR_Controller.Input(index);
                        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
                        {
                            Vector2 touchpad = (device.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0));


                            if (touchpad.y < 0.7f)
                            {
                                ActiveController = obj;

                                Pointer.transform.parent        = obj.transform;
                                Pointer.transform.localPosition = Vector3.zero;
                                Pointer.transform.localRotation = Quaternion.identity;
                                Pointer.transform.localScale    = Vector3.one;
                                Pointer.enabled = true;

                                CurrentTeleportState = TeleportState.Selecting;
                            }
                            // Set active controller to this controller, and enable the parabolic pointer and visual indicators
                            // that the user can use to determine where they are able to teleport.


                            if (NavmeshAnimator != null)
                            {
                                NavmeshAnimator.SetBool(EnabledAnimatorID, true);
                            }

                            Pointer.ForceUpdateCurrentAngle();
                            LastClickAngle = Pointer.CurrentPointVector;
                            IsClicking     = Pointer.PointOnNavMesh;
                        }
                    }
                }
            }
            if (isright)
            {
                // If we are currently teleporting (ie handling the fade in/out transition)...
                if (CurrentTeleportState == TeleportState.Teleporting)
                {
                    // Wait until half of the teleport time has passed before the next event (note: both the switch from fade
                    // out to fade in and the switch from fade in to stop the animation is half of the fade duration)
                    if (Time.time - TeleportTimeMarker >= TeleportFadeDuration / 2)
                    {
                        if (FadingIn)
                        {
                            // We have finished fading in
                            CurrentTeleportState = TeleportState.None;
                        }
                        else
                        {
                            // We have finished fading out - time to teleport!
                            Vector3 offset = OriginTransform.position - HeadTransform.position;
                            offset.y = 0;
                            OriginTransform.position = Pointer.SelectedPoint + offset;
                        }

                        TeleportTimeMarker = Time.time;
                        FadingIn           = !FadingIn;
                    }
                }
                // At this point, we are NOT actively teleporting.  So now we care about controller input.
                else if (CurrentTeleportState == TeleportState.Selecting)
                {
                    Debug.Assert(ActiveController != null);

                    // Here, there is an active controller - that is, the user is holding down on the trackpad.
                    // Poll controller for pertinent button data
                    int  index          = (int)ActiveController.index;
                    var  device         = SteamVR_Controller.Input(index);
                    bool shouldTeleport = device.GetPressUp(SteamVR_Controller.ButtonMask.Touchpad);
                    bool shouldCancel   = device.GetPressUp(SteamVR_Controller.ButtonMask.Grip);
                    if (shouldTeleport || shouldCancel)
                    {
                        // If the user has decided to teleport (ie lets go of touchpad) then remove all visual indicators
                        // related to selecting things and actually teleport
                        // If the user has decided to cancel (ie squeezes grip button) then remove visual indicators and do nothing
                        if (shouldTeleport && Pointer.PointOnNavMesh)
                        {
                            // Begin teleport sequence
                            CurrentTeleportState = TeleportState.Teleporting;
                            TeleportTimeMarker   = Time.time;
                        }
                        else
                        {
                            CurrentTeleportState = TeleportState.None;
                        }

                        // Reset active controller, disable pointer, disable visual indicators
                        ActiveController   = null;
                        Pointer.enabled    = false;
                        RoomBorder.enabled = false;
                        //RoomBorder.Transpose = Matrix4x4.TRS(OriginTransform.position, Quaternion.identity, Vector3.one);
                        if (NavmeshAnimator != null)
                        {
                            NavmeshAnimator.SetBool(EnabledAnimatorID, false);
                        }

                        Pointer.transform.parent     = null;
                        Pointer.transform.position   = Vector3.zero;
                        Pointer.transform.rotation   = Quaternion.identity;
                        Pointer.transform.localScale = Vector3.one;
                    }
                    else
                    {
                        // The user is still deciding where to teleport and has the touchpad held down.
                        // Note: rendering of the parabolic pointer / marker is done in ParabolicPointer
                        Vector3 offset = HeadTransform.position - OriginTransform.position;
                        offset.y = 0;

                        // Render representation of where the chaperone bounds will be after teleporting
                        RoomBorder.enabled   = Pointer.PointOnNavMesh;
                        RoomBorder.Transpose = Matrix4x4.TRS(Pointer.SelectedPoint - offset, Quaternion.identity, Vector3.one);

                        // Haptic feedback click every [HaptickClickAngleStep] degrees
                        if (Pointer.CurrentParabolaAngleY >= 45) // Don't click when at max degrees
                        {
                            LastClickAngle = Pointer.CurrentPointVector;
                        }

                        float angleClickDiff = Vector3.Angle(LastClickAngle, Pointer.CurrentPointVector);
                        if (IsClicking && Mathf.Abs(angleClickDiff) > HapticClickAngleStep)
                        {
                            LastClickAngle = Pointer.CurrentPointVector;
                            if (Pointer.PointOnNavMesh)
                            {
                                device.TriggerHapticPulse();
                            }
                        }

                        // Trigger a stronger haptic pulse when "entering" a teleportable surface
                        if (Pointer.PointOnNavMesh && !IsClicking)
                        {
                            IsClicking = true;
                            device.TriggerHapticPulse(750);
                            LastClickAngle = Pointer.CurrentPointVector;
                        }
                        else if (!Pointer.PointOnNavMesh && IsClicking)
                        {
                            IsClicking = false;
                        }
                    }
                }
                else //CurrentTeleportState == TeleportState.None
                {
                    // At this point the user is not holding down on the touchpad at all or has canceled a teleport and hasn't
                    // let go of the touchpad.  So we wait for the user to press the touchpad and enable visual indicators
                    // if necessary.
                    foreach (SteamVR_TrackedObject obj in Controllers)
                    {
                        int index = (int)obj.index;
                        if (index == -1)
                        {
                            continue;
                        }

                        var device = SteamVR_Controller.Input(index);
                        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
                        {
                            Vector2 touchpad = (device.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0));


                            if (touchpad.y < 0.7f)
                            {
                                ActiveController = obj;

                                Pointer.transform.parent        = obj.transform;
                                Pointer.transform.localPosition = Vector3.zero;
                                Pointer.transform.localRotation = Quaternion.identity;
                                Pointer.transform.localScale    = Vector3.one;
                                Pointer.enabled = true;

                                CurrentTeleportState = TeleportState.Selecting;
                            }
                            // Set active controller to this controller, and enable the parabolic pointer and visual indicators
                            // that the user can use to determine where they are able to teleport.


                            if (NavmeshAnimator != null)
                            {
                                NavmeshAnimator.SetBool(EnabledAnimatorID, true);
                            }

                            Pointer.ForceUpdateCurrentAngle();
                            LastClickAngle = Pointer.CurrentPointVector;
                            IsClicking     = Pointer.PointOnNavMesh;
                        }
                    }
                }
            }
        }
    }
Esempio n. 17
0
 private void SetDeviceIndex(int index)
 {
     DeviceIndex = index;
     Controller  = SteamVR_Controller.Input(index);
 }
Esempio n. 18
0
    void Update()
    {
        _trackedObject = GetComponent <SteamVR_TrackedObject>();
        _device        = SteamVR_Controller.Input((int)_trackedObject.index);
        _touchPosition = _device.GetAxis();

        if (_isCanvasMode)
        {
            if (_device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
            {
                switch (GetTouchPositionOfGamePad())
                {
                case 0:
                    //When clicking on the top
                    ExecuteEvents.Execute <IColorCanvas>(
                        target: _system,
                        eventData: null,
                        functor: (reciever, y) => reciever.ChangeHead(1)
                        );
                    break;

                case 2:
                    //When clicking on the under
                    ExecuteEvents.Execute <IColorCanvas>(
                        target: _system,
                        eventData: null,
                        functor: (reciever, y) => reciever.ChangeHead(-1)
                        );
                    break;

                case 1:
                    //When clicking on the ringt
                    ExecuteEvents.Execute <IColorCanvas>(
                        target: _system,
                        eventData: null,
                        functor: (reciever, y) => reciever.ChangeValue(10)
                        );
                    break;

                case 3:
                    //When clicking on the left
                    ExecuteEvents.Execute <IColorCanvas>(
                        target: _system,
                        eventData: null,
                        functor: (reciever, y) => reciever.ChangeValue(-10)
                        );
                    break;

                default:
                    break;
                }
            }
        }
        else
        {
            //トリガーを離した
            if (_device.GetTouchUp(SteamVR_Controller.ButtonMask.Trigger))
            {
                ReleaseObject();
            }

            //タッチパッドをクリック
            if (_device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
            {
                _toolMode = GetTouchPositionOfGamePad();
                ChangeTool(_toolMode);
            }

            if (_device.GetPressDown(SteamVR_Controller.ButtonMask.Grip))
            {
                InstantiateGrid();
            }
        }
    }
Esempio n. 19
0
    void Update()
    {
        foreach (var index in controllerIndices)
        {
            var overlay = SteamVR_Overlay.instance;
            if (overlay && point && pointer)
            {
                var t = SteamVR_Controller.Input(index).transform;
                pointer.transform.localPosition = t.pos;
                pointer.transform.localRotation = t.rot;

                var results = new SteamVR_Overlay.IntersectionResults();
                var hit     = overlay.ComputeIntersection(t.pos, t.rot * Vector3.forward, ref results);
                if (hit)
                {
                    point.transform.localPosition = results.point;
                    point.transform.localRotation = Quaternion.LookRotation(results.normal);
                }

                continue;
            }

            foreach (var buttonId in buttonIds)
            {
                if (SteamVR_Controller.Input(index).GetPressDown(buttonId))
                {
                    //Debug.Log(buttonId + " press down");
                    if (SteamVR_Controller.Input(index).GetPressUp(buttonId))
                    {
                        //Debug.Log(buttonId + " press up");
                        if (buttonId == EVRButtonId.k_EButton_SteamVR_Trigger)
                        {
                            SteamVR_Controller.Input(index).TriggerHapticPulse();
                            PrintControllerStatus(index);
                        }
                    }
                }
                if (SteamVR_Controller.Input(index).GetPress(buttonId))
                {
                    Debug.Log(buttonId);
                }
            }

            foreach (var buttonId in axisIds)
            {
                if (SteamVR_Controller.Input(index).GetTouchDown(buttonId))
                {
                    Debug.Log(buttonId + " touch down");
                }
                if (SteamVR_Controller.Input(index).GetTouchUp(buttonId))
                {
                    Debug.Log(buttonId + " touch up");
                }
                if (SteamVR_Controller.Input(index).GetTouch(buttonId))
                {
                    var axis = SteamVR_Controller.Input(index).GetAxis(buttonId);
                    Debug.Log("axis: " + axis);
                }
            }
        }
    }
Esempio n. 20
0
 void Start()
 {
     controllerIndex = (uint)trackedController.index;
     device          = SteamVR_Controller.Input((int)controllerIndex);
 }
 private void TriggerPressed(object sender, ClickedEventArgs e)
 {
     ShootPaintball();
     SteamVR_Controller.Input((int)trackedObj.index).TriggerHapticPulse(2500);
 }
Esempio n. 22
0
    // Update is called once per frame
    void Update()
    {
        float x;
        float y;

        SteamVR_TrackedObject trackedObjWandr = wandr.GetComponent <SteamVR_TrackedObject> ();
        SteamVR_TrackedObject trackedObjWandl = wandl.GetComponent <SteamVR_TrackedObject> ();

        SteamVR_Controller.Device deviceR = null;
        SteamVR_Controller.Device deviceL = null;

        if (trackedObjWandr != null)
        {
            deviceR = SteamVR_Controller.Input((int)trackedObjWandr.index);
        }
        if (trackedObjWandr != null)
        {
            deviceL = SteamVR_Controller.Input((int)trackedObjWandl.index);
        }

        //Hold for a few iterations in order not to enter the loop several times in a row with the same interaction
        count += 1;

        x = deviceR.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad).x;
        y = deviceR.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad).y;

        if (x != 0 || y != 0)
        {
            if (y > 0)     //top Part of pad
            {
                if (x > 0) //Top Right
                {
                    if (y > x)
                    {
                    }
                    else
                    {
                        isNormalized = false;
                        SetDataText(lastGrabbedObject);
                    }
                }
                else//Top Left
                {
                    if (y > -x)
                    {
                    }
                    else
                    {
                        isNormalized = true;
                        SetDataText(lastGrabbedObject);
                    }
                }
            }
            else//bottom part of pad
            {
                if (x > 0)//bottom Right
                {
                    if (-y > x)
                    {
                    }
                    else
                    {
                        isNormalized = false;
                        SetDataText(lastGrabbedObject);
                    }
                }
                else//bottom Left
                {
                    if (-y > -x)
                    {
                    }
                    else
                    {
                        isNormalized = true;
                        SetDataText(lastGrabbedObject);
                    }
                }
            }
        }

        if (deviceR.GetPress(SteamVR_Controller.ButtonMask.Trigger))
        {
            if (grabbedObject == null)
            {
                if (currentObject != null)
                {
                    grabbedObject = currentObject;

                    // If object had a rigidbody, grabbed save the rigidbody's kinematic state
                    // so it can be restored on release of the object
                    Rigidbody body = null;

                    body = grabbedObject.GetComponent <Rigidbody> ();
                    if (body != null)
                    {
                        wasKinematic     = body.isKinematic;
                        body.isKinematic = true;
                    }

                    //Read the parameters of the data Point(Dont kn ow if I will put this here or not)
                    // Save away to original parentage of the grabbed object
                    if (grabbedObject.tag == "attr")
                    {
                        grabbedObjectParent = attrHolder.transform;
                    }
                    else
                    {
                        // Save away to original parentage of the grabbed object
                        grabbedObjectParent = grabbedObject.transform.parent;
                    }

                    // Make the grabbed object a child of the wand
                    grabbedObject.transform.parent = wandr.transform;
                    currentObject = null;

                    // Disable collision between yourself and the grabbed object so that the grabbed object
                    // does not apply its physics to you and push you off the world
                    Physics.IgnoreCollision(cameraRig.GetComponent <Collider>(), grabbedObject.GetComponent <Collider>(), true);

                    if (deviceR.GetPress(SteamVR_Controller.ButtonMask.Grip))
                    {
                        if (grabbedObject.GetComponent <AttrProperties> ().inWorld == true)
                        {
                            if (grabbedObject.GetComponent <AttrProperties> ().isActive == true)
                            {
                                grabbedObject.GetComponent <AttrProperties> ().isActive = false;
                                grabbedObject.GetComponent <Light>().enabled            = false;
                            }
                            else
                            {
                                if (attrCycle == 0)
                                {
                                    grabbedObject.GetComponent <AttrProperties> ().isActive = true;
                                    grabbedObject.GetComponent <Light>().enabled            = true;
                                    grabbedObjectParent = attrHolder.transform;
                                    attrCycle           = 1;
                                }
                                else if (attrCycle == 1)
                                {
                                    grabbedObject.GetComponent <AttrProperties> ().inWorld = false;
                                    grabbedObjectParent = attrArm.transform;
                                    attrCycle           = 0;
                                }
                            }
                        }
                        else
                        {
                            grabbedObject.GetComponent <AttrProperties> ().inWorld = true;
                            grabbedObjectParent = attrHolder.transform;
                        }
                        count = 0;
                    }
                }
            }
        }
        else
        {
            if (grabbedObject != null)
            {
                // Restore the original parentage of the grabbed object
                grabbedObject.transform.parent = grabbedObjectParent;

                // If object had a rigidbody, restore its kinematic state
                Rigidbody body = null;
                body = grabbedObject.GetComponent <Rigidbody> ();
                if (body != null)
                {
                    body.isKinematic = wasKinematic;
                }

                // Re-enstate collision between self and object
                Physics.IgnoreCollision(cameraRig.GetComponent <Collider> (), grabbedObject.GetComponent <Collider> (), false);

                grabbedObject = null;
                currentObject = null;
            }
        }
    }
Esempio n. 23
0
    public void UpdateComponents(CVRRenderModels renderModels)
    {
        if (renderModels == null)
        {
            return;
        }

        var t = transform;

        if (t.childCount == 0)
        {
            return;
        }

        var controllerState = (index != SteamVR_TrackedObject.EIndex.None)
            ? SteamVR_Controller.Input((int)index).GetState()
            : new VRControllerState_t();

        if (nameCache == null)
        {
            nameCache = new Dictionary <int, string>();
        }

        for (int i = 0; i < t.childCount; i++)
        {
            var child = t.GetChild(i);

            // Cache names since accessing an object's name allocate memory.
            string name;
            if (!nameCache.TryGetValue(child.GetInstanceID(), out name))
            {
                name = child.name;
                nameCache.Add(child.GetInstanceID(), name);
            }

            var componentState = new RenderModel_ComponentState_t();
            if (
                !renderModels.GetComponentState(renderModelName, name, ref controllerState, ref controllerModeState,
                                                ref componentState))
            {
                continue;
            }

            var componentTransform = new SteamVR_Utils.RigidTransform(componentState.mTrackingToComponentRenderModel);
            child.localPosition = componentTransform.pos;
            child.localRotation = componentTransform.rot;

            var attach = child.FindChild(k_localTransformName);
            if (attach != null)
            {
                var attachTransform = new SteamVR_Utils.RigidTransform(componentState.mTrackingToComponentLocal);
                attach.position = t.TransformPoint(attachTransform.pos);
                attach.rotation = t.rotation * attachTransform.rot;
            }

            bool visible = (componentState.uProperties & (uint)EVRComponentProperty.IsVisible) != 0;
            if (visible != child.gameObject.activeSelf)
            {
                child.gameObject.SetActive(visible);
            }
        }
    }
Esempio n. 24
0
    public void CheckController(SteamVR_TrackedObject controller)
    {
        SteamVR_Controller.Device input = null;
        if (controller != null)
        {
            input = SteamVR_Controller.Input((int)controller.index);
        }

        Vector3    origin;
        Vector3    direction;
        Quaternion rotation;

        origin    = controller.transform.position;
        direction = controller.transform.rotation * new Vector3(0, 0, 100);
        rotation  = controller.transform.rotation;

        bool hitScreen = false;

        // Mouse simulation
        if (Visible())
        {
            RaycastHit[] rcasts = Physics.RaycastAll(origin, direction);

            foreach (RaycastHit rcast in rcasts)
            {
                if (rcast.collider.gameObject != this.gameObject)
                {
                    continue;
                }

                hitScreen = true;

                if (m_manager.ShowLine)
                {
                    m_line.enabled = true;
                    m_line.SetPosition(0, origin);
                    m_line.SetPosition(1, rcast.point);
                }
                else
                {
                    m_line.enabled = false;
                }

                //
                float dx = m_manager.GetScreenWidth(ScreenId);
                float dy = m_manager.GetScreenHeight(ScreenId);

                Vector2 offset = m_manager.GetScreenOffset(this);

//                float vx = rcast.textureCoord.x * m_manager.textureScale;
//                float vy = rcast.textureCoord.y * m_manager.textureScale;
                float vx = rcast.textureCoord.x;
                float vy = rcast.textureCoord.y;

                vy = 1 - vy;

                float x = (vx * dx) + offset.x;
                float y = (vy * dy) + offset.y;

                int iX = (int)x;
                int iY = (int)y;

//                Debug.Log($"{x} {y} {ScreenId}");

                m_manager.SetCursorPos(iX, iY);

                if (m_lastShowClick == 0)
                {
                    //if (m_manager.EnableZoom)
                    if (m_manager.ViveZoom != VdmDesktopManager.ViveButton.None)
                    {
                        if (input.GetPressDown(MyButtonToViveButton(m_manager.ViveZoom)))
                        {
                            VdmDesktopManager.ActionInThisFrame = true;

                            m_distanceBeforeZoom = (controller.transform.position - rcast.point).magnitude;

                            float distanceDelta = m_distanceBeforeZoom - m_manager.ControllerZoomDistance;

                            Vector3 vectorMove = rotation * new Vector3(0, 0, -distanceDelta);

                            m_positionZoomed = m_positionNormal + vectorMove;
                            m_rotationZoomed = m_rotationNormal;

                            //m_positionZoomed = controller.transform.position + controller.transform.rotation * new Vector3(0, 0, m_manager.ControllerZoomDistance);

                            ZoomIn();
                        }
                        if (input.GetPressUp(MyButtonToViveButton(m_manager.ViveZoom)))
                        {
                            VdmDesktopManager.ActionInThisFrame = true;

                            ZoomOut();
                        }
                    }
                }

                if (m_manager.ViveLeftClick != VdmDesktopManager.ViveButton.None)
                {
                    if (input.GetPressDown(MyButtonToViveButton(m_manager.ViveLeftClick)))
                    {
                        m_lastLeftTriggerClick = Time.time;
                        m_manager.SimulateMouseLeftDown();
                        VdmDesktopManager.ActionInThisFrame = true;
                    }

                    if (input.GetPressUp(MyButtonToViveButton(m_manager.ViveLeftClick)))
                    {
                        if (m_lastLeftTriggerClick != 0)
                        {
                            m_manager.SimulateMouseLeftUp();
                            m_lastLeftTriggerClick = 0;
                            VdmDesktopManager.ActionInThisFrame = true;
                        }
                    }
                }

                if (m_manager.ViveTouchPadForClick)
                {
                    if (input.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad) && (input.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0).x < -0.2f))
                    {
                        m_lastLeftTouchClick = Time.time;
                        m_manager.SimulateMouseLeftDown();
                        VdmDesktopManager.ActionInThisFrame = true;
                    }

                    if (input.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad) && (input.GetAxis(Valve.VR.EVRButtonId.k_EButton_Axis0).x > -0.2f))
                    {
                        m_lastRightTouchClick = Time.time;
                        m_manager.SimulateMouseRightDown();
                        VdmDesktopManager.ActionInThisFrame = true;
                    }
                }
                if (m_lastLeftTouchClick != 0)
                {
                    if (input.GetPressUp(SteamVR_Controller.ButtonMask.Touchpad))
                    {
                        m_manager.SimulateMouseLeftUp();
                        m_lastLeftTouchClick = 0;
                        VdmDesktopManager.ActionInThisFrame = true;
                    }
                }

                if (m_lastRightTouchClick != 0)
                {
                    if (input.GetPressUp(SteamVR_Controller.ButtonMask.Touchpad))
                    {
                        m_manager.SimulateMouseRightUp();
                        m_lastRightTouchClick = 0;
                        VdmDesktopManager.ActionInThisFrame = true;
                    }
                }
            }
        }


        if ((Visible() == false) || (hitScreen))
        {
            if (input.GetPressDown(MyButtonToViveButton(m_manager.ViveShow)))
            {
                if (m_lastShowClick == 0)
                {
                    VdmDesktopManager.ActionInThisFrame = true;

                    if (hitScreen == false)
                    {
                        Show();

                        // Don't set m_positionNormal.
                        Vector3 startDistance = controller.transform.rotation * new Vector3(0, 0, m_manager.ControllerZoomDistance);
                        transform.position = controller.transform.position + startDistance;
                        transform.rotation = controller.transform.rotation;

                        m_lastShowClick = Time.time - 10;
                    }
                    else
                    {
                        m_lastShowClick = Time.time;
                    }
                    transform.SetParent(controller.transform);
                    m_controllerAttach = true;
                }
            }
        }

        if (input.GetPressUp(MyButtonToViveButton(m_manager.ViveShow)))
        {
            if (m_lastShowClick != 0)
            {
                if (Time.time - m_lastShowClick < 0.5f)
                {
                    Hide();
                }

                VdmDesktopManager.ActionInThisFrame = true;
                m_lastShowClick = 0;
                transform.SetParent(m_manager.transform);
                m_controllerAttach = false;
                m_positionNormal   = transform.position;
                m_rotationNormal   = transform.rotation;
            }
        }
    }
 public override void Haptic(float Time)
 {
     SteamVR_Controller.Input((int)m_trackedController.controllerIndex).TriggerHapticPulse((ushort)(Time * 1000));
 }
Esempio n. 26
0
 protected void InitDevice()
 {
     m_device = SteamVR_Controller.Input((int)m_tracked.index);
 }
Esempio n. 27
0
            private void Update()
            {
                if (m_deviceController)
                {
                    //Renew Objects
                    m_lineManager.Renew();
                    m_rodManagement.Renew();

                    //Rod Controll
                    SteamVR_Controller.Device device = SteamVR_Controller.Input((int)m_deviceController.index);

                    m_currentForce = m_lineManager.Spring.currentForce;

                    if (reelModel)
                    {
                        reelModel.localEulerAngles =
                            new Vector3(
                                0f,
                                0f,
                                reelModel.localEulerAngles.z + m_controllerClass.ReelAngularVelocity
                                );
                    }

                    //釣り竿の投げに関する処理
                    if (m_releaseTriger)
                    {
                        //投げた直後
                        if (m_threadLength == float.PositiveInfinity)
                        {
                            //着水したら
                            if (m_lineManager.FishingHook.transform.position.y <= 0f || m_lineManager.FishingHookInstance.IsCollision)
                            {
                                m_lineManager.Spring.spring = 100000000f;

                                m_threadLength = (
                                    m_lineManager.Spring.transform.position -
                                    m_lineManager.FishingHook.transform.position).magnitude;

                                m_lineManager.Spring.maxDistance = m_threadLength;

                                if (m_lineManager.FishingHookInstance)
                                {
                                    m_lineManager.FishingHookInstance.IsFishing = true;
                                }

                                GameManagement.main.startFIshing();

                                Debug.Log(m_threadLength + " meter");
                            }
                            //ルアー着水後
                        }
                        else
                        {
                            float value = m_controllerClass.ReelAngularVelocity;

                            float reelSpd = 0.0025f;

                            if (m_threadLength <= 0f)
                            {
                                GameManagement.main.standby();
                                m_lineManager.FishingHookInstance.IsFishing = false;
                            }

                            if (GameManagement.main.gamePhase == GameManagement.GamePhase.ExpireYarn)
                            {
                                reelSpd = 0.02f;
                            }

                            if (value > 0.1f)
                            {
                                m_threadLength -= value * reelSpd;
                            }

                            GUITextLog.main.println(m_threadLength + "m");

                            GUITextLog.main.println(m_lineManager.Spring.currentForce.magnitude + "");
                            //gui_debug_3dLine.main.draw( m_lineManager.FishingHook.position, m_lineManager.FishingHook.position + m_lineManager.Spring.currentForce );

                            if (m_threadLength <= 0f)
                            {
                                //ゲームクリア処理
                                if (m_lineManager.FishingHookInstance.GetFish)
                                {
                                    Vehicle.Boat.main.hangFish(m_lineManager.FishingHookInstance.GetFish);

                                    m_lineManager.FishingHookInstance.GetFish.DeleteFish();

                                    GameManagement.main.getFish();
                                }

                                returnLure();
                            }

                            if (m_threadLength > 8f && Random.Range(0f, 1f) <= 0.05f && m_lineManager.FishingHookInstance.GetFish)
                            {
                                Ray        ray = new Ray(RodTip.position, m_lineManager.FishingHook.position - RodTip.position);
                                RaycastHit _Hit;
                                if (Physics.Raycast(ray, out _Hit, 500f, (int)Mathf.Pow(2, LayerMask.NameToLayer("Water"))))
                                {
                                    GameObject obj = Instantiate(GameManagement.main.effect_Splash);
                                    obj.transform.position = ray.origin + ray.direction.normalized * _Hit.distance;
                                    Destroy(obj, 3f);
                                }
                            }

                            //Debug.Log(value);

                            m_lineManager.Spring.maxDistance = m_threadLength;
                        }
                    }
                    else
                    {
                        m_lineManager.Spring.maxDistance = 0f;
                    }

                    /*
                     * //Debug
                     * if(m_lineManager.FishingHookInstance.IsFishing)
                     *      gui_debug_3dLine.main.setColor(Color.cyan);
                     * else
                     *      gui_debug_3dLine.main.setColor(Color.red);
                     *
                     * gui_debug_3dLine.main.draw(Float.transform.position,Float.transform.position + Vector3.up * 500f);
                     */
                }
                else
                {
                    if (m_controllerClass && m_controllerClass.ControllerTracker)
                    {
                        m_deviceController =
                            m_controllerClass.ControllerTracker;

                        StartCoroutine(C_Vibration());
                        StartCoroutine(C_CheckThrowRod());
                    }
                }
            }
 public void Start()
 {
     Device = SteamVR_Controller.Input((int)Controller.controllerIndex);
 }
Esempio n. 29
0
            //釣り竿の投げ判定
            private IEnumerator C_CheckThrowRod()
            {
                yield return(new WaitForSeconds(1f));

                bool isApproaching = false;

                float old_dot = float.NaN;

                float throwAngle = 45f;

                Vector3 throwVector =
                    Quaternion.Euler(-throwAngle, 0f, 0f) * Vector3.forward;

                SteamVR_Controller.Device device = SteamVR_Controller.Input((int)m_deviceController.index);

                Rigidbody rodRb = m_rodManagement.RodPartsList[1].GetComponent <Rigidbody>();

                while (true)
                {
                    if (!m_releaseTriger && GameManagement.main.gamePhase < GameManagement.GamePhase.GetFish)
                    {
                        float ang = 0f;

                        if (transform.up.y < 0.3f)
                        {
                            ang = Mathf.Atan2(-transform.up.x, -transform.up.z) * Mathf.Rad2Deg;
                        }
                        else
                        {
                            ang = Mathf.Atan2(transform.forward.x, transform.forward.z) * Mathf.Rad2Deg;
                            if (transform.position.y < transform.position.y - transform.up.y)
                            {
                                ang += 180f;
                            }
                        }

                        GUITextLog.main.println(transform.up.y + "");

                        throwVector =
                            Quaternion.Euler(-throwAngle, ang, 0f) * Vector3.forward;

                        Vector3 vel = m_lineManager.FishingHook.velocity;

                        //gui_debug_3dLine.main.draw(transform.position,transform.position + throwVector);

                        float dot = Vector3.Dot(throwVector, vel.normalized);

                        GUITextLog.main.println("" + rodRb.angularVelocity.x);

                        if (
                            rodRb.angularVelocity.x > 0.1f
                            )
                        {
                            if (
                                old_dot != float.NaN &&
                                dot > 0.5f &&
                                vel.magnitude > 12f
                                )
                            {
                                if (isApproaching)
                                {
                                    vel += Camera.main.transform.forward;
                                    m_lineManager.FishingHook.velocity += throwVector * vel.magnitude;
                                    m_lineManager.FishingHook.velocity /= 2f;

                                    m_releaseTriger = true;
                                    Debug.Log(vel.magnitude);
                                    releaseLure();
                                }
                            }
                        }

                        if (old_dot > dot)
                        {
                            isApproaching = true;
                        }
                        else
                        {
                            isApproaching = false;
                        }

                        old_dot = dot;

                        if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger))
                        {
                            Debug.Log(vel.magnitude + "");
                            if (vel.magnitude > 8f)
                            {
                                releaseLure();
                            }
                        }
                        else
                        {
                        }
                    }

                    /*
                     * gui_debug_3dLine.main.setColor(Color.red);
                     * gui_debug_3dLine.main.draw(
                     *      transform.position,
                     *      transform.position + throwVector
                     * );
                     *
                     * gui_debug_3dLine.main.setColor(Color.blue);
                     * gui_debug_3dLine.main.draw(
                     *      transform.position,
                     *      transform.position + transform.forward
                     * );
                     *
                     * Debug.Log(Vector3.Dot(throwVector,transform.forward));
                     */

                    yield return(new WaitForFixedUpdate());
                }
            }
Esempio n. 30
0
 private void SetDeviceIndex(int index)
 {
     DeviceIndex = index;
     Controller  = SteamVR_Controller.Input(index);
     StartCoroutine(DoInitialize());
 }
Esempio n. 31
0
 private bool IsTriggerPressed()
 {
     return(SteamVR_Controller.Input((int)RightController.index).GetPressDown(EVRButtonId.k_EButton_SteamVR_Trigger));
 }
    // Update is called once per frame
    void Update()
    {
        device = SteamVR_Controller.Input((int)controller.index);

        if (device.GetTouchDown(SteamVR_Controller.ButtonMask.Touchpad))
        {
            //load new scene
            //SteamVR_LoadLevel.Begin("Teleport");

            //reset position of finger to 0, 0 (I think)
            touchLast_x = device.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad).x;
            touchLast_y = device.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad).y;
        }

        //detect when our user is toucing the touchpad
        if (device.GetTouch(SteamVR_Controller.ButtonMask.Touchpad))
        {
            objMenu.SetActive(true);

            touchCurrent_x = device.GetAxis(Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad).x;
            //how much did the finger move this frame?
            distance_x = touchCurrent_x - touchLast_x;
            //cache our fingers location so we know where it was last frame
            touchLast_x = touchCurrent_x;
            //add the distance travelled to the swipeSum variable
            swipeSum_x += distance_x;
            if (!hasSwipedRight)
            {
                if (swipeSum_x > 0.5f)
                {
                    swipeSum_x = 0;
                    SwipeLeft();
                    hasSwipedRight = true;
                    hasSwipedLeft  = false;
                }
            }

            if (!hasSwipedLeft)
            {
                if (swipeSum_x < -0.5f)
                {
                    swipeSum_x = 0;
                    SwipeRight();
                    hasSwipedLeft  = true;
                    hasSwipedRight = false;
                }
            }
        }
        if (device.GetTouchUp(SteamVR_Controller.ButtonMask.Touchpad))
        {
            objMenu.SetActive(false);

            swipeSum_x     = 0;
            touchCurrent_x = 0;
            touchLast_x    = 0;
            hasSwipedLeft  = false;
            hasSwipedRight = false;
        }
        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad))
        {
            //spawn object currently selected by menu
            SpawnObject();

            //objectMenuManager.SpawnCurrentObject();
        }
        if (device.GetPressDown(SteamVR_Controller.ButtonMask.Grip))
        {
            objectMenuManager.DestroyObject();
        }
    }
Esempio n. 33
0
 private void Update()
 {
     foreach (int current in this.controllerIndices)
     {
         SteamVR_Overlay instance = SteamVR_Overlay.instance;
         if (instance && this.point && this.pointer)
         {
             SteamVR_Utils.RigidTransform transform = SteamVR_Controller.Input(current).transform;
             this.pointer.transform.localPosition = transform.pos;
             this.pointer.transform.localRotation = transform.rot;
             SteamVR_Overlay.IntersectionResults intersectionResults = default(SteamVR_Overlay.IntersectionResults);
             bool flag = instance.ComputeIntersection(transform.pos, transform.rot * Vector3.forward, ref intersectionResults);
             if (flag)
             {
                 this.point.transform.localPosition = intersectionResults.point;
                 this.point.transform.localRotation = Quaternion.LookRotation(intersectionResults.normal);
             }
         }
         else
         {
             EVRButtonId[] array = this.buttonIds;
             for (int i = 0; i < array.Length; i++)
             {
                 EVRButtonId eVRButtonId = array[i];
                 if (SteamVR_Controller.Input(current).GetPressDown(eVRButtonId))
                 {
                     Debug.Log(eVRButtonId + " press down");
                 }
                 if (SteamVR_Controller.Input(current).GetPressUp(eVRButtonId))
                 {
                     Debug.Log(eVRButtonId + " press up");
                     if (eVRButtonId == EVRButtonId.k_EButton_Axis1)
                     {
                         SteamVR_Controller.Input(current).TriggerHapticPulse(500, EVRButtonId.k_EButton_Axis0);
                         this.PrintControllerStatus(current);
                     }
                 }
                 if (SteamVR_Controller.Input(current).GetPress(eVRButtonId))
                 {
                     Debug.Log(eVRButtonId);
                 }
             }
             EVRButtonId[] array2 = this.axisIds;
             for (int j = 0; j < array2.Length; j++)
             {
                 EVRButtonId eVRButtonId2 = array2[j];
                 if (SteamVR_Controller.Input(current).GetTouchDown(eVRButtonId2))
                 {
                     Debug.Log(eVRButtonId2 + " touch down");
                 }
                 if (SteamVR_Controller.Input(current).GetTouchUp(eVRButtonId2))
                 {
                     Debug.Log(eVRButtonId2 + " touch up");
                 }
                 if (SteamVR_Controller.Input(current).GetTouch(eVRButtonId2))
                 {
                     Vector2 axis = SteamVR_Controller.Input(current).GetAxis(eVRButtonId2);
                     Debug.Log("axis: " + axis);
                 }
             }
         }
     }
 }