/// <summary> /// Gets the rotation of the given Hand local to its tracking space. /// </summary> public static Quaternion GetLocalHandRotation(OVRInput.Hand hand) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return Quaternion.identity; #else if (!OVRManager.isHmdPresent) return Quaternion.identity; #endif return OVRPlugin.GetNodePose((OVRPlugin.Node)hand).ToOVRPose().orientation; }
private void Update() { #if UNITY_EDITOR if (_scriptsReloaded) { _scriptsReloaded = false; instance = this; Initialize(); } #endif if (OVRPlugin.shouldQuit) { Application.Quit(); } if (OVRPlugin.shouldRecenter) { OVRManager.display.RecenterPose(); } if (trackingOriginType != _trackingOriginType) { trackingOriginType = _trackingOriginType; } tracker.isEnabled = usePositionTracking; OVRPlugin.rotation = useRotationTracking; OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking; // Dispatch HMD events. isHmdPresent = OVRPlugin.hmdPresent; if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel) { Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing + ", but the recommended MSAA level is " + display.recommendedMSAALevel + ". Switching to the recommended level."); QualitySettings.antiAliasing = display.recommendedMSAALevel; } if (_wasHmdPresent && !isHmdPresent) { try { if (HMDLost != null) { HMDLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasHmdPresent && isHmdPresent) { try { if (HMDAcquired != null) { HMDAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasHmdPresent = isHmdPresent; // Dispatch HMD mounted events. isUserPresent = OVRPlugin.userPresent; if (_wasUserPresent && !isUserPresent) { try { if (HMDUnmounted != null) { HMDUnmounted(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasUserPresent && isUserPresent) { try { if (HMDMounted != null) { HMDMounted(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasUserPresent = isUserPresent; // Dispatch VR Focus events. hasVrFocus = OVRPlugin.hasVrFocus; if (_hadVrFocus && !hasVrFocus) { try { if (VrFocusLost != null) { VrFocusLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadVrFocus && hasVrFocus) { try { if (VrFocusAcquired != null) { VrFocusAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadVrFocus = hasVrFocus; // Dispatch VR Input events. bool hasInputFocus = OVRPlugin.hasInputFocus; if (_hadInputFocus && !hasInputFocus) { try { if (InputFocusLost != null) { InputFocusLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadInputFocus && hasInputFocus) { try { if (InputFocusAcquired != null) { InputFocusAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadInputFocus = hasInputFocus; // Dispatch System Overlay present events. bool hasSystemOverlayPresent = OVRPlugin.hasSystemOverlayPresent; if (_hadSystemOverlayPresented && !hasSystemOverlayPresent) { try { if (SystemOverlayHide != null) { SystemOverlayHide(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadSystemOverlayPresented && hasSystemOverlayPresent) { try { if (SystemOverlayPresented != null) { SystemOverlayPresented(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadSystemOverlayPresented = hasSystemOverlayPresent; // Changing effective rendering resolution dynamically according performance #if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5_4_OR_NEWER if (enableAdaptiveResolution) { if (UnityEngine.XR.XRSettings.eyeTextureResolutionScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation UnityEngine.XR.XRSettings.eyeTextureResolutionScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.XR.XRSettings.eyeTextureResolutionScale); } minRenderScale = Mathf.Min(minRenderScale, maxRenderScale); float minViewportScale = minRenderScale / UnityEngine.XR.XRSettings.eyeTextureResolutionScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.XR.XRSettings.eyeTextureResolutionScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); UnityEngine.XR.XRSettings.renderViewportScale = recommendedViewportScale; } #endif // Dispatch Audio Device events. string audioOutId = OVRPlugin.audioOutId; if (!prevAudioOutIdIsCached) { prevAudioOutId = audioOutId; prevAudioOutIdIsCached = true; } else if (audioOutId != prevAudioOutId) { try { if (AudioOutChanged != null) { AudioOutChanged(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioOutId = audioOutId; } string audioInId = OVRPlugin.audioInId; if (!prevAudioInIdIsCached) { prevAudioInId = audioInId; prevAudioInIdIsCached = true; } else if (audioInId != prevAudioInId) { try { if (AudioInChanged != null) { AudioInChanged(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioInId = audioInId; } // Dispatch tracking events. if (wasPositionTracked && !tracker.isPositionTracked) { try { if (TrackingLost != null) { TrackingLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!wasPositionTracked && tracker.isPositionTracked) { try { if (TrackingAcquired != null) { TrackingAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } wasPositionTracked = tracker.isPositionTracked; display.Update(); OVRInput.Update(); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (enableMixedReality || prevEnableMixedReality) { Camera mainCamera = FindMainCamera(); if (Camera.main != null) { suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false; if (enableMixedReality) { OVRMixedReality.Update(this.gameObject, mainCamera, compositionMethod, useDynamicLighting, capturingCameraDevice, depthQuality); } if (prevEnableMixedReality && !enableMixedReality) { OVRMixedReality.Cleanup(); } prevEnableMixedReality = enableMixedReality; } else { if (!suppressDisableMixedRealityBecauseOfNoMainCameraWarning) { Debug.LogWarning("Main Camera is not set, Mixed Reality disabled"); suppressDisableMixedRealityBecauseOfNoMainCameraWarning = true; } } } #endif }
// Update is called once per frame void Update() { float length = 100.0f; RaycastHit hit; Vector3 rayDirection = cameraTransform.TransformDirection(Vector3.forward); Vector3 rayStart = cameraTransform.position + rayDirection; if (Physics.Raycast(rayStart, rayDirection, out hit, length)) { if (hit.collider.tag == "Object") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { Vector3 newPos = hit.transform.position; newPos.y += 2f; hit.transform.position = newPos; } // Do stuff } if (hit.collider.tag == "Camera") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { this.transform.position = hit.transform.position; this.GetComponent <AudioSource>().Play(0); if (hit.transform.gameObject.name != "MiddleLocation") { this.transform.LookAt(GameObject.Find("MiddleSword").transform); } //this.transform.rotation = hit.transform.rotation; } // Do stuff } if (hit.collider.tag == "Player") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { MeshRenderer temp = this.transform.Find("NameCard").GetComponent <MeshRenderer>(); temp.enabled = true; } // Do stuff } if (hit.collider.tag == "Map1") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { SceneManager.LoadScene(hit.collider.tag); } } if (hit.collider.tag == "Map2") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { SceneManager.LoadScene(hit.collider.tag); } } if (hit.collider.tag == "Map3") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { SceneManager.LoadScene(hit.collider.tag); } } if (hit.collider.tag == "Map4") { if (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)) { SceneManager.LoadScene(hit.collider.tag); } } } }
/// <summary> /// Gets the linear acceleration of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerAcceleration(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandLeft).ToOVRPose().position; case Controller.RTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandRight).ToOVRPose().position; default: return Vector3.zero; } }
private void Update() { if (OVRPlugin.shouldQuit) { Application.Quit(); } if (OVRPlugin.shouldRecenter) { OVRManager.display.RecenterPose(); } if (trackingOriginType != _trackingOriginType) { trackingOriginType = _trackingOriginType; } tracker.isEnabled = usePositionTracking; OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking; // Dispatch HMD events. isHmdPresent = OVRPlugin.hmdPresent; if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel) { Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing + ", but the recommended MSAA level is " + display.recommendedMSAALevel + ". Switching to the recommended level."); QualitySettings.antiAliasing = display.recommendedMSAALevel; } if (_wasHmdPresent && !isHmdPresent) { try { if (HMDLost != null) { HMDLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasHmdPresent && isHmdPresent) { try { if (HMDAcquired != null) { HMDAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasHmdPresent = isHmdPresent; // Dispatch HMD mounted events. isUserPresent = OVRPlugin.userPresent; if (_wasUserPresent && !isUserPresent) { try { if (HMDUnmounted != null) { HMDUnmounted(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasUserPresent && isUserPresent) { try { if (HMDMounted != null) { HMDMounted(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasUserPresent = isUserPresent; // Dispatch VR Focus events. hasVrFocus = OVRPlugin.hasVrFocus; if (_hadVrFocus && !hasVrFocus) { try { if (VrFocusLost != null) { VrFocusLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadVrFocus && hasVrFocus) { try { if (VrFocusAcquired != null) { VrFocusAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadVrFocus = hasVrFocus; // Changing effective rendering resolution dynamically according performance #if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5 && !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3) if (enableAdaptiveResolution) { if (VR.VRSettings.renderScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation VR.VRSettings.renderScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, VR.VRSettings.renderScale); } float minViewportScale = minRenderScale / VR.VRSettings.renderScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / VR.VRSettings.renderScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); VR.VRSettings.renderViewportScale = recommendedViewportScale; } #endif // Dispatch Audio Device events. string audioOutId = OVRPlugin.audioOutId; if (!prevAudioOutIdIsCached) { prevAudioOutId = audioOutId; prevAudioOutIdIsCached = true; } else if (audioOutId != prevAudioOutId) { try { if (AudioOutChanged != null) { AudioOutChanged(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioOutId = audioOutId; } string audioInId = OVRPlugin.audioInId; if (!prevAudioInIdIsCached) { prevAudioInId = audioInId; prevAudioInIdIsCached = true; } else if (audioInId != prevAudioInId) { try { if (AudioInChanged != null) { AudioInChanged(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioInId = audioInId; } // Dispatch tracking events. if (wasPositionTracked && !tracker.isPositionTracked) { try { if (TrackingLost != null) { TrackingLost(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!wasPositionTracked && tracker.isPositionTracked) { try { if (TrackingAcquired != null) { TrackingAcquired(); } } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } wasPositionTracked = tracker.isPositionTracked; display.Update(); OVRInput.Update(); }
void Update() { if (GameManager.Instance.m_gameStarted && !canUseEMP) { empTimer -= Time.unscaledDeltaTime; if (empTimer <= 0) { canUseEMP = true; buttonsUI.SetTrigger("On"); holdTimer = 0; } } if (GameManager.Instance.m_gameStarted) { if (OVRInput.Get(OVRInput.Button.One) && OVRInput.Get(OVRInput.Button.Three)) { charging = true; holdTimer += Time.unscaledDeltaTime; } if ((OVRInput.GetUp(OVRInput.Button.One) || OVRInput.GetUp(OVRInput.Button.Three)) && charging) { charging = false; canUseEMP = false; if (holdTimer >= GameManager.Instance.m_greenInterval.x && holdTimer <= GameManager.Instance.m_greenInterval.y) { EMP.Play(); GameManager.Instance.CheckForDead(); buttonsUI.SetTrigger("Fade"); empTimer = EMPintervalCorrect; } else { buttonsUI.SetTrigger("Wrong"); empTimer = EMPintervalWrong; } GameManager.Instance.AddEvent(holdTimer); } } if (Input.GetKeyDown(KeyCode.M)) { EMP.Play(); GameManager.Instance.CheckForDead(); } if (m_uiCanvas.worldCamera != m_head) { m_uiCanvas.worldCamera = m_head; } if (GameManager.Instance.m_gameStarted && !done) { m_livesUI[0].gameObject.GetComponentInParent <CanvasGroup>().alpha = 1f; done = true; } timer += Time.fixedUnscaledDeltaTime; if (timer >= lifeGainInterval) { timer = 0; m_currentLives++; m_currentLives = Mathf.Clamp(m_currentLives, 0, 5); } }
/// <summary> /// Gets the rotation of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Quaternion GetLocalControllerRotation(OVRInput.Controller controllerType) { if (!OVRManager.isHmdPresent) return Quaternion.identity; switch (controllerType) { case Controller.LTouch: return GetLocalHandRotation(OVRInput.Hand.Left); case Controller.RTouch: return GetLocalHandRotation(OVRInput.Hand.Right); default: return Quaternion.identity; } }
private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; System.Version netVersion = OVRPlugin.wrapperVersion; System.Version ovrVersion = OVRPlugin.version; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Utilities v" + netVersion + ", " + "OVRPlugin v" + ovrVersion + "."); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.Direct3D11) Debug.LogWarning("VR rendering requires Direct3D11. Your graphics device: " + SystemInfo.graphicsDeviceType); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; //isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR // We want to set up our touchpad messaging system OVRTouchpad.Create(); // Turn off chromatic aberration by default to save texture bandwidth. chromatic = false; #endif InitVolumeController(); if (display == null) display = new OVRDisplay(); if (tracker == null) tracker = new OVRTracker(); if (input == null) input = new OVRInput(); if (resetTrackerOnLoad) display.RecenterPose(); }
public virtual void UpdateMovement() { if (this.HaltUpdateMovement) { return; } if (this.EnableLinearMovement) { bool flag = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool flag2 = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool flag3 = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool flag4 = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); bool flag5 = false; if (OVRInput.Get(OVRInput.Button.DpadUp, OVRInput.Controller.Active)) { flag = true; flag5 = true; } if (OVRInput.Get(OVRInput.Button.DpadDown, OVRInput.Controller.Active)) { flag4 = true; flag5 = true; } this.MoveScale = 1f; if ((flag && flag2) || (flag && flag3) || (flag4 && flag2) || (flag4 && flag3)) { this.MoveScale = 0.707106769f; } if (!this.Controller.isGrounded) { this.MoveScale = 0f; } this.MoveScale *= this.SimulationRate * Time.deltaTime; float num = this.Acceleration * 0.1f * this.MoveScale * this.MoveScaleMultiplier; if (flag5 || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { num *= 2f; } Vector3 eulerAngles = base.transform.rotation.eulerAngles; eulerAngles.z = (eulerAngles.x = 0f); Quaternion rotation = Quaternion.Euler(eulerAngles); if (flag) { this.MoveThrottle += rotation * (base.transform.lossyScale.z * num * Vector3.forward); } if (flag4) { this.MoveThrottle += rotation * (base.transform.lossyScale.z * num * this.BackAndSideDampen * Vector3.back); } if (flag2) { this.MoveThrottle += rotation * (base.transform.lossyScale.x * num * this.BackAndSideDampen * Vector3.left); } if (flag3) { this.MoveThrottle += rotation * (base.transform.lossyScale.x * num * this.BackAndSideDampen * Vector3.right); } num = this.Acceleration * 0.1f * this.MoveScale * this.MoveScaleMultiplier; num *= 1f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.Active); Vector2 vector = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, OVRInput.Controller.Active); if (this.FixedSpeedSteps > 0) { vector.y = Mathf.Round(vector.y * (float)this.FixedSpeedSteps) / (float)this.FixedSpeedSteps; vector.x = Mathf.Round(vector.x * (float)this.FixedSpeedSteps) / (float)this.FixedSpeedSteps; } if (vector.y > 0f) { this.MoveThrottle += rotation * (vector.y * base.transform.lossyScale.z * num * Vector3.forward); } if (vector.y < 0f) { this.MoveThrottle += rotation * (Mathf.Abs(vector.y) * base.transform.lossyScale.z * num * this.BackAndSideDampen * Vector3.back); } if (vector.x < 0f) { this.MoveThrottle += rotation * (Mathf.Abs(vector.x) * base.transform.lossyScale.x * num * this.BackAndSideDampen * Vector3.left); } if (vector.x > 0f) { this.MoveThrottle += rotation * (vector.x * base.transform.lossyScale.x * num * this.BackAndSideDampen * Vector3.right); } } if (this.EnableRotation) { Vector3 eulerAngles2 = base.transform.rotation.eulerAngles; float num2 = this.SimulationRate * Time.deltaTime * this.RotationAmount * this.RotationScaleMultiplier; bool flag6 = OVRInput.Get(OVRInput.Button.PrimaryShoulder, OVRInput.Controller.Active); if (flag6 && !this.prevHatLeft) { eulerAngles2.y -= this.RotationRatchet; } this.prevHatLeft = flag6; bool flag7 = OVRInput.Get(OVRInput.Button.SecondaryShoulder, OVRInput.Controller.Active); if (flag7 && !this.prevHatRight) { eulerAngles2.y += this.RotationRatchet; } this.prevHatRight = flag7; eulerAngles2.y += this.buttonRotation; this.buttonRotation = 0f; if (!this.SkipMouseRotation) { eulerAngles2.y += Input.GetAxis("Mouse X") * num2 * 3.25f; } if (this.SnapRotation) { if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickLeft, OVRInput.Controller.Active)) { if (this.ReadyToSnapTurn) { eulerAngles2.y -= this.RotationRatchet; this.ReadyToSnapTurn = false; } } else if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickRight, OVRInput.Controller.Active)) { if (this.ReadyToSnapTurn) { eulerAngles2.y += this.RotationRatchet; this.ReadyToSnapTurn = false; } } else { this.ReadyToSnapTurn = true; } } else { Vector2 vector2 = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick, OVRInput.Controller.Active); eulerAngles2.y += vector2.x * num2; } base.transform.rotation = Quaternion.Euler(eulerAngles2); } }
IEnumerator Tutorial() { TutorialText.gameObject.SetActive(true); timer = 5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "Look arround and move.."; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "by moving your head"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "We give you magic power"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "Draw magic pattern"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "by holding and pressing"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "thumb A button"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); timer = 0.5f; yield return(new WaitForSeconds(timer)); before.gameObject.SetActive(true); timer = 1f; yield return(new WaitForSeconds(timer)); while (!OVRInput.GetDown(OVRInput.Button.One)) { yield return(null); } when.gameObject.SetActive(true); while (!OVRInput.GetUp(OVRInput.Button.One)) { yield return(null); } when.gameObject.SetActive(false); timer = 2f; yield return(new WaitForSeconds(timer)); before.gameObject.SetActive(false); TutorialText.text = "make C gesture"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 2f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "make Heart gesture"; timer = 0.5f; yield return(new WaitForSeconds(timer)); cmove.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); cmove.gameObject.SetActive(false); timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "make Down gesture"; timer = 0.5f; yield return(new WaitForSeconds(timer)); heartmove.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); heartmove.gameObject.SetActive(false); timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "Creating the same weapon cube"; timer = 0.5f; yield return(new WaitForSeconds(timer)); downmove.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); downmove.gameObject.SetActive(false); timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); before.gameObject.SetActive(false); TutorialText.text = "will delete the previous cube."; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "There's hidden combo"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "That lies in your hand"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "Defeat your enemy"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "by throwing weapon cube."; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); TutorialText.text = "Good luck"; timer = 0.5f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(true); timer = 3f; yield return(new WaitForSeconds(timer)); TutorialText.gameObject.SetActive(false); timer = 0.5f; yield return(new WaitForSeconds(timer)); musuh.SetActive(true); tv.SetActive(false); }
void Update() { var pointer = Pointer; // コントローラーを取得 // コントローラーがない or LineRendererがなければ何もしない if (pointer == null || _LaserPointerRenderer == null) { return; } // コントローラー位置からRayを飛ばす Ray pointerRay = new Ray(pointer.position, pointer.forward); // レーザーの起点 _LaserPointerRenderer.SetPosition(0, pointerRay.origin); RaycastHit hitInfo; if (Physics.Raycast(pointerRay, out hitInfo, _MaxDistance)) { // Rayがヒットしたらそこまで _LaserPointerRenderer.SetPosition(1, hitInfo.point); /* ---以下追加した部分--- */ // ヒットしたオブジェクトを取得 GameObject obj = hitInfo.collider.gameObject; // ヒットしたオブジェクトのScaleを取得 //Vector3 scale = obj.transform.localScale; if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)) { // トリガーボタンを押した時 if (obj.tag == "AnswerArea") { GameObject image = Instantiate(_TrueImage, pointerRay.origin + pointerRay.direction * 150, Quaternion.LookRotation(pointerRay.direction)); ScoreManager.addScore(20); image.GetComponentInChildren <RawImage>().CrossFadeAlpha(0.0f, 1.0f, true); SceneManager.LoadScene("tete4"); } else { GameObject image = Instantiate(_FalseImage, pointerRay.origin + pointerRay.direction * 150, Quaternion.LookRotation(pointerRay.direction)); // fade out image.GetComponentInChildren <RawImage>().CrossFadeAlpha(0.0f, 1.0f, true); //SceneManager.LoadScene("tete4"); } //Vector3 maxScale = new Vector3(5f,5f,5f); //messageText1.GetComponent<TextMesh>.guiText = "Good // messageText1.SetActive(true); // スケールの各値が5より小さい場合は0.1大きくする //if (scale.sqrMagnitude < maxScale.sqrMagnitude) { //obj.transform.localScale = new Vector3 (scale.x + 0.1f, scale.y + 0.1f, scale.z + 0.1f); //} } /*else if (OVRInput.GetDown(OVRInput.Button.PrimaryTouchpad)) { * // タッチパッドボタンを押した時 * Vector3 minScale = new Vector3(0.5f,0.5f,0.5f); * // スケールの各値が0.5より大きい場合は0.1小さくする * if (scale.sqrMagnitude > minScale.sqrMagnitude) { * obj.transform.localScale = new Vector3 (scale.x - 0.1f, scale.y - 0.1f, scale.z - 0.1f); * } * }*/ /* ---追加した部分ここまで--- */ } else { // Rayがヒットしなかったら向いている方向にMaxDistance伸ばす _LaserPointerRenderer.SetPosition(1, pointerRay.origin + pointerRay.direction * _MaxDistance); if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)) { GameObject image = Instantiate(_FalseImage, pointerRay.origin + pointerRay.direction * 150, Quaternion.LookRotation(pointerRay.direction)); image.GetComponentInChildren <RawImage>().CrossFadeAlpha(0.0f, 1.0f, true); SceneManager.LoadScene("tete4"); } } }
private void CheckInputSource() { //Update m_InputSource = UpdateSource(OVRInput.GetActiveController(), m_InputSource); }
ControllerPose GetControllerPose(OVRInput.Controller controller) { ovrAvatarButton buttons = 0; if (OVRInput.Get(OVRInput.Button.One, controller)) { buttons |= ovrAvatarButton.One; } if (OVRInput.Get(OVRInput.Button.Two, controller)) { buttons |= ovrAvatarButton.Two; } if (OVRInput.Get(OVRInput.Button.Start, controller)) { buttons |= ovrAvatarButton.Three; } if (OVRInput.Get(OVRInput.Button.PrimaryThumbstick, controller)) { buttons |= ovrAvatarButton.Joystick; } ovrAvatarTouch touches = 0; if (OVRInput.Get(OVRInput.Touch.One, controller)) { touches |= ovrAvatarTouch.One; } if (OVRInput.Get(OVRInput.Touch.Two, controller)) { touches |= ovrAvatarTouch.Two; } if (OVRInput.Get(OVRInput.Touch.PrimaryThumbstick, controller)) { touches |= ovrAvatarTouch.Joystick; } if (OVRInput.Get(OVRInput.Touch.PrimaryThumbRest, controller)) { touches |= ovrAvatarTouch.ThumbRest; } if (OVRInput.Get(OVRInput.Touch.PrimaryIndexTrigger, controller)) { touches |= ovrAvatarTouch.Index; } if (!OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, controller)) { touches |= ovrAvatarTouch.Pointing; } if (!OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, controller)) { touches |= ovrAvatarTouch.ThumbUp; } return(new ControllerPose { buttons = buttons, touches = touches, joystickPosition = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, controller), indexTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, controller), handTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, controller), isActive = (OVRInput.GetActiveController() & controller) != 0, }); }
/// <summary> /// Gets the angular acceleration of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Quaternion GetLocalControllerAngularAcceleration(OVRInput.Controller controllerType) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return Quaternion.identity; #else if (!OVRManager.isHmdPresent) return Quaternion.identity; #endif switch (controllerType) { case Controller.LTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandLeft).ToOVRPose().orientation; case Controller.RTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandRight).ToOVRPose().orientation; default: return Quaternion.identity; } }
/// <summary> /// Gets the rotation of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Quaternion GetLocalControllerRotation(OVRInput.Controller controllerType) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return Quaternion.identity; #else if (!OVRManager.isHmdPresent) return Quaternion.identity; #endif switch (controllerType) { case Controller.LTouch: return GetLocalHandRotation(OVRInput.Hand.Left); case Controller.RTouch: return GetLocalHandRotation(OVRInput.Hand.Right); default: return Quaternion.identity; } }
// Update is called once per frame void Update() { if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger) && OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger)) { current_scale = gameObject.transform.localScale; distance_hand_init = Vector3.Distance(l_hand.transform.position, r_hand.transform.position); Debug.Log("pressed"); } if (OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger) && OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger) && OVRInput.Get(OVRInput.Button.SecondaryHandTrigger)) { distance_hand_end = Vector3.Distance(l_hand.transform.position, r_hand.transform.position); factor_scale = (distance_hand_end / distance_hand_init); new_scale = current_scale * factor_scale; } gameObject.transform.localScale = new_scale; }
private IEnumerator StopVibrationAfter(float duration) { yield return(new WaitForSeconds(duration)); OVRInput.SetControllerVibration(0, 0, controllerMask); }
// Update is called once per frame void Update() { // yama 181224 DeviceContoroll.csに評価を行う提示パターンを受け渡し if (prePattern != feedbackPattern) { dc.Set_FeedbackPattern(feedbackPattern); prePattern = feedbackPattern; } // yama 181228 練習環境から切り替わった際,評価対象のオブジェクトはここで選択される if (objT == null) { objT = oe.Set_EvaluationObject(eNum); if (objT.activeSelf) { Get_EvaluationObj(objT); } } // yama 190201 実験1実施時 if (eNum == 1) { // yama 190201 実験実施時はコントローラ,デバックや動作確認の際はキーボードで仮想物体の切り替え if (OVRInput.GetDown(OVRInput.RawButton.LIndexTrigger) || Input.GetKeyDown(KeyCode.Space)) { if (contactP) { if (!oe.Set_PointFlag()) { #region ファイルに出力するための変数を集め,合体 string pene = dc.Set_PenetrationDistance(); // yama 181120 現在のめり込み量を取得 string peneY = dc.Set_PenetYDistance(); // yama 181120 現在のY軸方向のめり込み量を取得 Vector3 tipPos = dc.Set_tipD(); // yama 190201 現フレームのデバイス先端座標 Vector3 hitPos = dc.Set_hitO(); // yama 190201 現フレームのデバイスの方向ベクトルと仮想ぶった表面の交点(真値) double sitaRV = dc.Set_AngleRVNormal(); // yama 190201 接触点の法線と床の法線とのなす角 double sitaDeV = dc.Set_AngleDeVNormal(); // yama 190201 接触点の法線とデバイスの方向ベクトルのなす角 double sitaDeR = dc.Set_AngleDeRNormal(); // yama 190201 床の法線とデバイスの方向ベクトルのなす角 string txt = pene + "," + peneY + ",,," + tipPos.x + "," + tipPos.y + "," + tipPos.z + ",,," + +hitPos.x + "," + hitPos.y + "," + hitPos.z + ",," + sitaRV + "," + sitaDeV + "," + sitaDeR; Text_Save(txt); #endregion objP.GetComponent <ChangeObjColor>().Change_Color(0); oe.Set_NextEvaluation(); timer.Stop(); timer.Reset(); } } else { Debug.Log("ERROR:ポイントに対して接触していません."); } } // yama 190201 デバックや動作確認時,途中で終了するとそれまでのデータが保存されないので,強制終了用 if (Input.GetKeyDown(KeyCode.M)) { swIn.Flush(); swIn.Close(); Debug.Log("Save Finish"); } contactP = false; } // yama 190201 実験2実施時 else if (eNum == 2) { // yama 190201 実験実施時はコントローラ,デバックや動作確認の際はキーボードで仮想物体の切り替え if (OVRInput.GetDown(OVRInput.RawButton.LIndexTrigger) || Input.GetKeyDown(KeyCode.Space)) { objT = oe.Set_EvaluationObject(eNum); if (objT.activeSelf) { Debug.Log("Name: " + objT.name); Get_EvaluationObj(objT); } } if (start) { #region ファイルに出力するための変数を集め,合体 string pene = dc.Set_PenetrationDistance(); // yama 181120 現在のめり込み量を取得 string peneY = dc.Set_PenetYDistance(); // yama 181120 現在のY軸方向のめり込み量を取得 Vector3 tipPos = dc.Set_tipD(); Vector3 hitPos = dc.Set_hitO(); double sitaRV = dc.Set_AngleRVNormal(); double sitaDeV = dc.Set_AngleDeVNormal(); double sitaDeR = dc.Set_AngleDeRNormal(); string txt = pene + "," + peneY + ",,," + tipPos.x + "," + tipPos.y + "," + tipPos.z + ",,," + +hitPos.x + "," + hitPos.y + "," + hitPos.z + ",," + sitaRV + "," + sitaDeV + "," + sitaDeR; Text_Save(txt); #endregion } } }
private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; System.Version netVersion = OVRPlugin.wrapperVersion; System.Version ovrVersion = OVRPlugin.version; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Integration v" + netVersion + ", " + "OVRPlugin v" + ovrVersion + "."); // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if !UNITY_ANDROID || UNITY_EDITOR if (OVRUnityVersionChecker.hasBuiltInVR) { Debug.LogWarning("The Oculus Unity Legacy Integration is only supported in Unity 4.x releases. For Unity 5.x, please migrate to the Oculus Utilities for Unity package and use Unity's built-in VR support (available in Unity 5.1 and later)."); isVRPresent = false; } else if (!ovrIsInitialized) { //HACK: For some reason, Unity doesn't call UnitySetGraphicsDevice until we make the first P/Invoke call. OVRPluginEvent.eventBase = OVRPluginEvent.eventBase; #if !UNITY_ANDROID || UNITY_EDITOR //Handle all log messages OVR_FlushLog(OnLogMessage); #endif // If unable to load the Oculus Runtime. if (!OVRPlugin.initialized) { bool isBadWinRenderer = ((Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) && !SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")); if (isBadWinRenderer) Debug.LogWarning("Only D3D11 is supported on Windows."); else Debug.LogWarning("Runtime is not present or no Rift attached. Running without VR."); // Runtime is not installed if ovr_Initialize() fails. isVRPresent = false; // Go monoscopic in response. monoscopic = true; } else { OVRPluginEvent.Issue(RenderEventType.InitRenderThread); isVRPresent = true; #if UNITY_EDITOR if (!OVRUnityVersionChecker.hasEditorVRSupport) { // Only allow VR in standalones. isVRPresent = false; Debug.LogWarning("VR rendering is not supported in the editor. Please update to 4.6.7p4 or build a stand-alone player."); } #endif if (netVersion.Major > ovrVersion.Major || netVersion.Major == ovrVersion.Major && netVersion.Minor > ovrVersion.Minor) { isVRPresent = false; Debug.LogWarning("Version check failed. Please make sure you are using OVRPlugin " + Ovr.Hmd.OVR_VERSION_STRING + " or newer."); } OVRPlugin.queueAheadFraction = 0f; ovrIsInitialized = true; } } SetEditorPlay(Application.isEditor); #else // UNITY_ANDROID && !UNITY_EDITOR: Start of Android init. // Android integration does not dynamically load its runtime. isVRPresent = true; // log the unity version Debug.Log( "Unity Version: " + Application.unityVersion ); // don't allow the application to run if orientation is not landscape left. if (Screen.orientation != ScreenOrientation.LandscapeLeft) { Debug.LogError("********************************************************************************\n"); Debug.LogError("***** Default screen orientation must be set to landscape left for VR.\n" + "***** Stopping application.\n"); Debug.LogError("********************************************************************************\n"); Debug.Break(); Application.Quit(); } // don't enable gyro, it is not used and triggers expensive display calls if (Input.gyro.enabled) { Debug.LogError("*** Auto-disabling Gyroscope ***"); Input.gyro.enabled = false; } // NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the // main window surface with front buffer rendering enabled. The view will // render black. // On Adreno KitKat, some tiling control modes will cause the view to render // black. if (QualitySettings.antiAliasing > 1) { Debug.LogError("*** Antialiasing must be disabled for Gear VR ***"); } // we sync in the TimeWarp, so we don't want unity // syncing elsewhere QualitySettings.vSyncCount = 0; // try to render at 60fps Application.targetFrameRate = 60; // don't allow the app to run in the background Application.runInBackground = false; // Disable screen dimming Screen.sleepTimeout = SleepTimeout.NeverSleep; if (!androidJavaInit) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); // Prepare for the RenderThreadInit() SetInitVariables(activity.GetRawObject(), System.IntPtr.Zero); #if USE_ENTITLEMENT_CHECK AndroidJavaObject entitlementChecker = new AndroidJavaObject("com.oculus.svclib.OVREntitlementChecker"); entitlementChecker.CallStatic("doAutomatedCheck", activity); #else Debug.Log( "Inhibiting Entitlement Check!" ); #endif androidJavaInit = true; } // We want to set up our touchpad messaging system OVRTouchpad.Create(); InitVolumeController(); // set an event delegate like this if you wish to handle events like "reorient". //SetVrApiEventDelegate( VrApiEventDefaultDelegate ); #endif // End of android init. prevEyeTextureAntiAliasing = OVRManager.instance.eyeTextureAntiAliasing; prevEyeTextureDepth = OVRManager.instance.eyeTextureDepth; prevEyeTextureFormat = OVRManager.instance.eyeTextureFormat; prevNativeTextureScale = OVRManager.instance.nativeTextureScale; prevVirtualTextureScale = OVRManager.instance.virtualTextureScale; prevMonoscopic = OVRManager.instance.monoscopic; prevHdr = OVRManager.instance.hdr; if (tracker == null) tracker = new OVRTracker(); if (display == null) display = new OVRDisplay(); else wasRecreated = true; if (input == null) input = new OVRInput(); if (resetTrackerOnLoad) display.RecenterPose(); #if !UNITY_ANDROID || UNITY_EDITOR // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps(). if (timeWarp) { bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"); QualitySettings.vSyncCount = useUnityVSync ? 1 : 0; QualitySettings.maxQueuedFrames = 0; } #endif #if UNITY_STANDALONE_WIN if (!OVRUnityVersionChecker.hasD3D9ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9")) { MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } if (!OVRUnityVersionChecker.hasD3D11ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")) { MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } #endif }
// Update is called once per frame void Update() { transform.localPosition = OVRInput.GetLocalControllerPosition(controller); transform.localRotation = OVRInput.GetLocalControllerRotation(controller); }
/// <summary> /// Gets the local Hand rotation of the given Hand. /// </summary> public static Quaternion GetLocalHandRotation(OVRInput.Hand hand) { if (!OVRManager.instance.isVRPresent) return Quaternion.identity; return OVRPlugin.GetNodePose((OVRPlugin.Node)hand+3).ToOVRPose().orientation; }
void Update() { #if UNITY_STANDALONE || UNITY_EDITOR if (Input.GetKeyDown(actionKey)) { laneTriggerDown(Input.GetKey(KeyCode.RightShift)); } if (Input.GetKeyUp(actionKey)) { laneTriggerUp(); } #endif if (beatBoxArrival != null) { playBeatBox(currentTime()); } if (isAlreadyInside)//allow some recoding inputs while inside (hold, directional, regular through directional press? { if (InputUtils.getDirectionalDown(triggeredByRightController)) { int direction = InputUtils.getDirectionalPress(triggeredByRightController); if (direction >= 0) { //boxType = SongRow.BoxType.DIR_N + direction; registeredBeat.type = SongRow.BoxType.DIR_N + direction; } else { registeredBeat.type = SongRow.BoxType.REGULAR; } } if (InputUtils.isHoldKeyDown(triggeredByRightController)) { registeredBeat.type = SongRow.BoxType.MAYBE_HOLD; registeredBeat.timestamp = currentTime() - seekOffset(); } } if (isEnabledLaneAudio) { if ((isAlreadyInside || audioModSelected) && InputUtils.isLoopKeyDown(triggeredByRightController)) { switchLooping(); } if (isAlreadyInside || audioModSelected) { bool audioModifierKeys = InputUtils.isEffectBKeyPressed(triggeredByRightController) || InputUtils.isEffectAKeyPressed(triggeredByRightController); if (audioModifierKeys) { applyAudioMods(); } } float growth = audioSource.time / audioSource.clip.length; audioProgress.transform.localScale = new Vector3(growth, growth, growth); if (beatPlayMode == BeatPlayMode.TRIGGER_IMMEDIATE && wasAudioTriggered) { audioSource.Play(); wasAudioTriggered = false; } else if (isNewBeat()) {//in sync with bpm, so all samples start at the same time //instead of isLooping, 3 states: idle, loopToBeat, loopToAudio //also, trigger mode to ignore beat sync and play once at once //TODO option to set lane skip beats (loop clip stops and doesn't restart until n skips) //variable skips can create useful effects for drums/snares,...? //skipBeat = !skipBeat; //if (skipBeat) //{ // if (beatPlayMode == BeatPlayMode.LOOP_TO_BEAT) // { // audioSource.Stop(); // } //} //else switch (beatPlayMode) { case BeatPlayMode.TRIGGER_IN_BEAT: if (audioSource.isPlaying) //this syncs audio end with next beat { audioSource.Stop(); } if (wasAudioTriggered) { audioSource.Play(); wasAudioTriggered = false; } break; case BeatPlayMode.TRIGGER_TO_BEAT: if (wasAudioTriggered) { audioSource.Play(); wasAudioTriggered = false; } break; case BeatPlayMode.LOOP_TO_BEAT: if (wasAudioTriggered) { audioSource.Play(); } else { audioSource.Stop(); } break; case BeatPlayMode.LOOP_TO_AUDIO: if (wasAudioTriggered && !audioSource.isPlaying) { audioSource.Play(); } break; } } } //TODO?: this is so that boxes can be recorded while already inside the lane end (triggered) if (isEnabledModelling && spawningBlock != null && !InputUtils.isDragPressed(triggeredByRightController)) { //save final position spawningBlock.transform.parent = null; spawningBlock.transform.eulerAngles = Vector3.zero; spawningBlock = null; } //checking user dragging the lane (or creating a build block) if (handTransform != null) { if (isEnabledModelling) { if (isAlreadyInside && InputUtils.isDragDown(triggeredByRightController)) { spawningBlock = Instantiate(blockPrefab);//FurnitureSpawner.spawn(f, blockPrefab); spawningBlock.transform.position = handTransform.position; spawningBlock.transform.parent = handTransform; Utils.resizeToMatch(spawningBlock, gameObject); } } else { if (InputUtils.isDragDown(triggeredByRightController)) { grabOffset = -(transform.parent.position - handTransform.position) / 2; lastDragPosition = Vector3.zero; } //if (grabOffset != Vector3.zero && InputUtils.isDragPressed(triggeredByRightController)) if (grabOffset != Vector3.zero) { if (InputUtils.isDragPressed(triggeredByRightController)) { //elapsedDragTime -= Time.deltaTime; //if (true ||Vector3.Distance(transform.parent.position, movingTransform.position - grabOffset) > Settings.distanceToDetectDrag)//0.25f) if (Vector3.Distance(lastDragPosition, handTransform.position - grabOffset) > Settings.distanceToDetectDrag) { registeredMove = new RegisteredMove(currentTime(), handTransform.position - grabOffset); //Debug.Log("Registering move to " + (movingTransform.position - grabOffset)); //elapsedDragTime = Settings.instance.laneDragTimeLapse; lastDragPosition = handTransform.position - grabOffset; } transform.parent.position = handTransform.position - grabOffset; } else { handTransform = null; grabOffset = Vector3.zero; } } } } if (Settings.instance.vibrationDuration > 0 && rightVibrationTime > 0 && rightVibrationTime <= Time.time) { OVRInput.SetControllerVibration(1.0f, 0, OVRInput.Controller.RTouch); rightVibrationTime = 0; } if (Settings.instance.vibrationDuration > 0 && leftVibrationTime > 0 && leftVibrationTime <= Time.time) { OVRInput.SetControllerVibration(1.0f, 0, OVRInput.Controller.LTouch); leftVibrationTime = 0; } }
/// <summary> /// Gets the linear acceleration of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerAcceleration(OVRInput.Controller controllerType) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return Vector3.zero; #else if (!OVRManager.isHmdPresent) return Vector3.zero; #endif switch (controllerType) { case Controller.LTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandLeft).ToOVRPose().position; case Controller.RTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandRight).ToOVRPose().position; default: return Vector3.zero; } }
void Update() { if (pointer == null) { return; } if (OVRInput.GetDown(OVRInput.Button.Any, OVRInput.Controller.RTrackedRemote) || OVRInput.GetDown(OVRInput.Button.Back, OVRInput.Controller.RTrackedRemote)) { Ray ray = new Ray(pointer.StartPoint, pointer.Forward); RaycastHit[] hits = Physics.RaycastAll(ray, 100f); foreach (RaycastHit hit in hits) { //Debug.Log ($"Hit {hit.transform.name}"); SelectionReactor reactor = GetReactorForHit(hit); if (reactor != null) { //Debug.Log ("Perform action"); reactor.Select(); if (!reactor.propogateHit) { break; } } } } }
// Update is called once per frame void Update() { //Debug.DrawLine(LeftHand.position, LeftHand.position + LeftHand.up*10); //Debug.DrawLine(RightHand.position, RightHand.position + RightHand.up * 10); bIsSelecting = (OVRInput.Get(OVRInput.Button.One) || OVRInput.Get(OVRInput.Button.Three)); //if (layerManager.isComputing) bIsSelecting = false; if (bIsSelecting) { lineRenderer.enabled = true; RaycastHit hit; // Does the ray intersect any objects excluding the player layer if (Physics.Raycast(RightHand.position, RightHand.forward, out hit, Mathf.Infinity, layerMask)) { bUsingRight = true; lineRenderer.SetPosition(0, RightHand.position); lineRenderer.SetPosition(1, hit.point); VRTrigger trigger = hit.collider.gameObject.GetComponent <VRTrigger>(); if (trigger) { trigger.StartCompute(); return; } Debug.DrawRay(RightHand.position, RightHand.forward * hit.distance, Color.yellow); MoveHighlight(hit.transform, hit); } else if (Physics.Raycast(LeftHand.position, LeftHand.forward, out hit, Mathf.Infinity, layerMask)) { bUsingRight = false; lineRenderer.SetPosition(0, LeftHand.position); lineRenderer.SetPosition(1, hit.point); VRTrigger trigger = hit.collider.gameObject.GetComponent <VRTrigger>(); if (trigger) { trigger.StartCompute(); return; } Debug.DrawRay(LeftHand.position, LeftHand.forward * hit.distance, Color.yellow); MoveHighlight(hit.transform, hit); } else { if (bUsingRight) { lineRenderer.SetPosition(0, RightHand.position); lineRenderer.SetPosition(1, RightHand.position + RightHand.forward * length); } else { lineRenderer.SetPosition(0, LeftHand.position); lineRenderer.SetPosition(1, LeftHand.position + LeftHand.forward * length); } } } else { lineRenderer.enabled = false; } }
void FixedUpdate() { teleArc.enabled = false; teleSpot.enabled = false; if (!controlsLocked) { RaycastHit hit = getGunArc(rigidbody.transform.position, OVRInput.GetLocalControllerRotation(OVRInput.GetActiveController()) * transform.forward, 12f, gravity); if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)) { Debug.Log("test"); //RayCastShoot(true); LockControls(); StartCoroutine(Move(hit.point + hit.normal * playerHeight, transform.forward, 2f)); gravity = hit.normal * -9.81f; focus.activate(); } xDir += Input.GetAxis("Mouse X") * sensitivity; yDir -= Input.GetAxis("Mouse Y") * sensitivity; if (yDir > 90) { yDir = 90; } else if (yDir < -90) { yDir = -90; } rigidbody.rotation = Quaternion.Euler(yDir, xDir, 0.0f); } }
private void FixedUpdate() { OVRInput.FixedUpdate(); }
// Token: 0x06005678 RID: 22136 RVA: 0x001DC650 File Offset: 0x001DAA50 private void Update() { if (OVRManager.instance != null) { OVRManager.instance.enabled = (VRSettings.enabled && this.IsInVRMode()); } if (this.TrackerAnchor != null) { if (OVRManager.instance != null && OVRManager.instance.enabled) { if (!this.TrackerAnchor.gameObject.activeSelf) { this.TrackerAnchor.gameObject.SetActive(true); } OVRPose pose = OVRManager.tracker.GetPose(0); this.TrackerAnchor.localPosition = pose.position; this.TrackerAnchor.localRotation = pose.orientation; } else if (this.TrackerAnchor.gameObject.activeSelf) { this.TrackerAnchor.gameObject.SetActive(false); } } bool flag = OVRManager.instance != null && OVRManager.instance.enabled && VRCInputManager.IsPresent(VRCInputManager.InputMethod.Oculus); OVRInput.Controller controller = OVRInput.GetConnectedControllers() & OVRInput.GetActiveController(); bool flag2 = VRCInputManager.LastInputMethod == VRCInputManager.InputMethod.Oculus; if (flag2) { this._areControllersAsleep = false; this._usingHandControllers = true; } else if (!this._areControllersAsleep) { if (this._usingHandControllers) { this._usingHandControllers = false; this._controllerSleepTimeoutStart = Time.unscaledTime; } if (Time.unscaledTime - this._controllerSleepTimeoutStart > 1f) { this._areControllersAsleep = true; VRCTrackingManager.OnHandControllerAsleep(); } } if (this.LeftHandAnchor != null) { if (flag && (controller & OVRInput.Controller.LTouch) != OVRInput.Controller.None && !this._areControllersAsleep) { if (!this.LeftHandAnchor.gameObject.activeSelf) { this.LeftHandAnchor.gameObject.SetActive(true); } this.LeftHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch); this.LeftHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch); } else if (this.LeftHandAnchor.gameObject.activeSelf) { this.LeftHandAnchor.gameObject.SetActive(false); } } if (this.RightHandAnchor != null) { if (flag && (controller & OVRInput.Controller.RTouch) != OVRInput.Controller.None && !this._areControllersAsleep) { if (!this.RightHandAnchor.gameObject.activeSelf) { this.RightHandAnchor.gameObject.SetActive(true); } this.RightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch); this.RightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch); } else if (this.RightHandAnchor.gameObject.activeSelf) { this.RightHandAnchor.gameObject.SetActive(false); } } }
/// <summary> /// Gets the position of the given Hand local to its tracking space. /// </summary> public static Vector3 GetLocalHandPosition(OVRInput.Hand hand) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return Vector3.zero; #else if (!OVRManager.isHmdPresent) return Vector3.zero; #endif return OVRPlugin.GetNodePose((OVRPlugin.Node)hand).ToOVRPose().position; }
void Update() { // Check left hand input if (OVRInput.GetDown(OVRInput.Button.PrimaryHandTrigger)) { if (!leftHandGrapple.RopeLoaded()) { leftHandGrapple.LaunchHook(leftHandGrapple.transform); } } if (OVRInput.GetUp(OVRInput.Button.PrimaryHandTrigger)) { if (leftHandGrapple.RopeLoaded()) { leftHandGrapple.DetachHook(); } } Vector2 leftAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick); float leftPush = leftAxis.y; if (leftHandGrapple.RopeLoaded()) { leftHandGrapple.ChangeLength(leftPush); } // Check right hand input if (OVRInput.GetDown(OVRInput.Button.SecondaryHandTrigger)) { if (!rightHandGrapple.RopeLoaded()) { rightHandGrapple.LaunchHook(rightHandGrapple.transform); } } if (OVRInput.GetUp(OVRInput.Button.SecondaryHandTrigger)) { if (rightHandGrapple.RopeLoaded()) { rightHandGrapple.DetachHook(); } } if (OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger)) { rightHandWeapon.Shoot(); } Vector2 rightAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick); float rightPush = rightAxis.y; if (rightHandGrapple.RopeLoaded()) { rightHandGrapple.ChangeLength(rightPush); } // Debug Lines DrawLine(lhLineRenderer, leftHandGrapple.transform); DrawLine(rhLineRenderer, rightHandGrapple.transform); }
/// <summary> /// Gets the position of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerPosition(OVRInput.Controller controllerType) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return Vector3.zero; #else if (!OVRManager.isHmdPresent) return Vector3.zero; #endif switch (controllerType) { case Controller.LTouch: return GetLocalHandPosition(OVRInput.Hand.Left); case Controller.RTouch: return GetLocalHandPosition(OVRInput.Hand.Right); default: return Vector3.zero; } }
// Update is called once per frame void Update() { //GetSpectrumAudioSource(); Player.position = Vector3.Lerp(Player.position, new Vector3(-0.4591381f, 2.035491f, -0.7840782f), Time.deltaTime); Opponent.position = Vector3.Lerp(Opponent.position, new Vector3(-0.137f, 2.035491f, -0.419f), Time.deltaTime); Opponent.rotation = Quaternion.Lerp(Opponent.rotation, oppTarget.rotation, Time.deltaTime); secondsCount += Time.deltaTime; //var axis = WaveVR_Controller.Input(device).GetAxis(WVR_InputId.WVR_InputId_Alias1_Touchpad); if (secondsCount >= 2.01) { for (int i = 0; i <= danceLights.Length - 1; i++) { if (i == lightsCounter) { danceLights[i].enabled = true; } else { danceLights[i].enabled = false; } } if (lightsCounter + 1 >= danceLights.Length) { lightsCounter = 0; } else { lightsCounter++; } secondsCount = 0; } switch (secCounter) { case 0: animator.SetBool("isDanceStart", true); dkAnim.SetBool("isDanceStart", true); break; case 1: //dkAnim.SetBool("Turn1", true); StartCoroutine(turnComments(ui.opponentComments, "My Turn!", "Show me what ya got!")); break; case 2: //dkAnim.SetBool("Turn1", false); isTurn = true; //ui.danceInstructions.SetActive(true); StartCoroutine(turnComments(ui.playerComments, "Here we go!", "Step it up!")); break; case 3: //dkAnim.SetBool("Turn2", true); isTurn = false; //ui.danceInstructions.SetActive(false); StartCoroutine(turnComments(ui.opponentComments, "Not bad!", "Back at ya!")); pointLcount = 0; pointRcount = 0; shakeLcount = 0; shakeRcount = 0; break; case 4: //dkAnim.SetBool("Turn2", false); isTurn = true; //ui.danceInstructions.SetActive(true); StartCoroutine(turnComments(ui.playerComments, "Groovy!", "Almost got it!")); break; case 5: isTurn = false; //ui.danceInstructions.SetActive(false); pointLcount = 0; pointRcount = 0; shakeLcount = 0; shakeRcount = 0; break; default: break; } if (isTurn) { /*if (WaveVR_Controller.Input(device).GetTouchDown(WVR_InputId.WVR_InputId_Alias1_Touchpad)) * { * if (axis.y >= 0.7 && axis.y <= 1.0) * { * log.text += " top"; * previousTouchState = "rShake"; * } * if (axis.y <= -0.7 && axis.y >= -1.0) * { * previousTouchState = "lShake"; * } * if (axis.x >= 0.7 && axis.x <= 1.0) * { * previousTouchState = "lPoint"; * } * if (axis.x <= -0.7 && axis.x >= -1.0) * { * previousTouchState = "rPoint"; * } * if (WaveVR_Controller.Input(device).GetPress(WVR_InputId.WVR_InputId_Alias1_Digital_Trigger)) * { * if (axis.y >= 0.7 && axis.y <= 1.0) * { * log.text += " top"; * previousTouchState = "splits"; * } * if (axis.y <= -0.7 && axis.y >= -1.0) * { * previousTouchState = "victory"; * } * } * } * * if (WaveVR_Controller.Input(device).GetTouchUp(WVR_InputId.WVR_InputId_Alias1_Touchpad)) * { * log.text = "Up"; * if (axis.y <= -0.7 && axis.y >= -1.0) * { * if (previousTouchState == "splits") * { * animator.SetBool("isSplits", true); * splitsCount++; * battleScore += gm.MoveScore("finishMove", splitsCount); * StartCoroutine(setAnimToFalse("isSplits")); * } * if (previousTouchState == "rShake") * { * animator.SetBool("isShakeR", true); * shakeRcount++; * battleScore += gm.MoveScore("basicMove", shakeRcount); * StartCoroutine(setAnimToFalse("isShakeR")); * } * } * if (axis.y >= 0.7 && axis.y <= 1.0) * { * if (previousTouchState == "victory") * { * animator.SetBool("isVictory", true); * victoryCount++; * battleScore += gm.MoveScore("finishMove", victoryCount); * StartCoroutine(setAnimToFalse("isVictory")); * } * if (previousTouchState == "lShake") * { * animator.SetBool("isShakeL", true); * shakeLcount++; * battleScore += gm.MoveScore("basicMove", shakeLcount); * StartCoroutine(setAnimToFalse("isShakeL")); * } * } * if (axis.x <= -0.7 && axis.x >= -1.0) * { * if (previousTouchState == "lPoint") * { * animator.SetBool("isPointL", true); * pointLcount++; * battleScore += gm.MoveScore("basicMove", pointLcount); * StartCoroutine(setAnimToFalse("isPointL")); * } * } * if (axis.x >= 0.7 && axis.x <= 1.0) * { * if (previousTouchState == "rPoint") * { * animator.SetBool("isPointR", true); * pointRcount++; * battleScore += gm.MoveScore("basicMove", pointRcount); * StartCoroutine(setAnimToFalse("isPointR")); * } * } * } * if (Input.GetKeyDown(KeyCode.Q)) * { * pointLcount++; * battleScore += gm.MoveScore("basicMove", pointLcount); * animator.SetBool("isPointL", true); * } * if (Input.GetKeyUp(KeyCode.Q)) * { * animator.SetBool("isPointL", false); * } * if (Input.GetKeyDown(KeyCode.W)) * { * pointRcount++; * battleScore += gm.MoveScore("basicMove", pointRcount); * animator.SetBool("isPointR", true); * } * if (Input.GetKeyUp(KeyCode.W)) * { * animator.SetBool("isPointR", false); * } * if (Input.GetKeyDown(KeyCode.A)) * { * shakeLcount++; * battleScore += gm.MoveScore("basicMove", shakeLcount); * animator.SetBool("isShakeL", true); * } * if (Input.GetKeyUp(KeyCode.A)) * { * animator.SetBool("isShakeL", false); * } * if (Input.GetKeyDown(KeyCode.S)) * { * shakeRcount++; * battleScore += gm.MoveScore("basicMove", shakeRcount); * animator.SetBool("isShakeR", true); * } * if (Input.GetKeyUp(KeyCode.S)) * { * animator.SetBool("isShakeR", false); * } * if (Input.GetKeyDown(KeyCode.E)) * { * victoryCount++; * battleScore += gm.MoveScore("finishMove", victoryCount); * animator.SetBool("isVictory", true); * } * if (Input.GetKeyUp(KeyCode.E)) * { * animator.SetBool("isVictory", false); * } * if (Input.GetKeyDown(KeyCode.D)) * { * splitsCount++; * battleScore += gm.MoveScore("finishMove", splitsCount); * animator.SetBool("isSplits", true); * } * if (Input.GetKeyUp(KeyCode.D)) * { * animator.SetBool("isSplits", false); * }*/ } Debug.Log(isBeat); if (isBeat) { if (OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger) || OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger)) { if (OVRInput.GetDown(OVRInput.Button.One)) { splitsCount++; battleScore += gm.MoveScore("finishMove", splitsCount); animator.SetBool("isSplits", true); StartCoroutine(setAnimToFalse("isSplits")); } else if (OVRInput.GetDown(OVRInput.Button.Two)) { victoryCount++; battleScore += gm.MoveScore("finishMove", victoryCount); animator.SetBool("isVictory", true); StartCoroutine(setAnimToFalse("isVictory")); } } else if (OVRInput.GetDown(OVRInput.Button.One)) { pointRcount++; battleScore += gm.MoveScore("basicMove", pointRcount); SetAnim("isPointR", "isShakeL", "isShakeR", "isPointL", animator); } else if (OVRInput.GetDown(OVRInput.Button.Two)) { pointLcount++; battleScore += gm.MoveScore("basicMove", pointLcount); SetAnim("isPointL", "isShakeL", "isPointR", "isShakeR", animator); } else if (OVRInput.GetDown(OVRInput.Button.Three)) { shakeLcount++; battleScore += gm.MoveScore("basicMove", shakeLcount); SetAnim("isShakeL", "isShakeR", "isPointR", "isPointL", animator); } else if (OVRInput.GetDown(OVRInput.Button.Four)) { shakeRcount++; battleScore += gm.MoveScore("basicMove", shakeRcount); SetAnim("isShakeR", "isShakeL", "isPointR", "isPointL", animator); } if (isBeat != isPreviousBeat) { Debug.Log("enemyBeat"); bool success = Random.value > 0.5f; if (success) { int move = Mathf.RoundToInt(Random.Range(0, 3)); if (move == 0) { SetAnim(danceSet[move], danceSet[move + 1], danceSet[move + 2], danceSet[move + 3], dkAnim); } else if (move == 1) { SetAnim(danceSet[move], danceSet[move - 1], danceSet[move + 1], danceSet[move + 2], dkAnim); } else if (move == 2) { SetAnim(danceSet[move], danceSet[move + 1], danceSet[move - 2], danceSet[move - 1], dkAnim); } else if (move == 3) { SetAnim(danceSet[move], danceSet[move - 1], danceSet[move - 2], danceSet[move - 3], dkAnim); } opBattleScore += MoveScore(); } } } ui.playerDanceScore.text = battleScore.ToString(); ui.opponentDanceScore.text = opBattleScore.ToString();; if (!audio.isPlaying) { foreach (Light light in danceLights) { light.enabled = false; } pm.enabled = true; barSnapshot.TransitionTo(1.0f); animator.SetBool("isDanceStart", false); dkAnim.SetBool("isDanceStart", false); ui.playerDanceScore.text = string.Empty; ui.opponentDanceScore.text = string.Empty; //battleScore += gm.theThreadz; /*if (battleScore > opBattleScore) * { * ui.win.enabled = true; * ui.winText.text = "You beat the Dance King!"; * gm.StartCoroutine(gm.winTimer()); * } * else if (battleScore < opBattleScore) * { * ui.win.enabled = true; * ui.winText.text = "Better luck next time!"; * gm.StartCoroutine(gm.winTimer()); * }*/ plot.SetActive(false); gameObject.AddComponent <DanceBattle>().enabled = false; ui.startDance.SetActive(true); ui.songCanvas.SetActive(true); Destroy(this); } isPreviousBeat = isBeat; }
//Emulate RWD vehicle, throttle applies torque to rear wheels public void accel() { /*//smart breaking, but issues if we hit something?? Allows for koyboard and joystick throttling and braking * if ((car.velocity.z > 0 && throttle < 0) || (car.velocity.z < 0 && throttle > 0)) * { * //try four wheel brakes * rearLeft.motorTorque = 0; * rearRight.motorTorque = 0; * rearLeft.brakeTorque = Math.Abs(throttle * brakes); * rearRight.brakeTorque = Math.Abs(throttle * brakes); * //frontLeft.brakeTorque = Math.Abs(throttle * brakes); * //frontRight.brakeTorque = Math.Abs(throttle * brakes); * * } * else if (throttle != 0) * { * //accel, 2 wheel (rear wheel) drive * rearLeft.brakeTorque = 0; * rearRight.brakeTorque = 0; * frontLeft.brakeTorque = 0; * frontRight.brakeTorque = 0; * rearLeft.motorTorque = throttle * force; * rearRight.motorTorque = throttle * force; * //frontLeft.motorTorque = throttle * force; //Enable these to enable AWD. Will be twice as fast unless you adjest force value. * //frontRight.motorTorque = throttle * force; * * //Could help with backing out of a stuck area * //if(car.velocity.z < 0 && throttle < 0) * //{ * // //reversing is kinda broken so do this * // rearLeft.motorTorque = throttle * force; * // rearRight.motorTorque = throttle * force; * // frontLeft.motorTorque = throttle * force; //Enable these to enable AWD. Will be twice as fast unless you adjest force value. * // frontRight.motorTorque = throttle * force; * //} * } * //else * //{ * // //i dont know * // rearLeft.motorTorque = throttle * force; * // rearRight.motorTorque = throttle * force; * // frontLeft.motorTorque = throttle * force; //Enable these to enable AWD. Will be twice as fast unless you adjest force value. * // frontRight.motorTorque = throttle * force; * //} */ //VR throttle and brake controlls rearLeft.motorTorque = throttle * force; rearRight.motorTorque = throttle * force; // if (car.velocity.z < -1 && throttle > .1f) { rearLeft.brakeTorque = brakes; rearRight.brakeTorque = brakes; //reduce power of front brakes to prevent flipping frontLeft.brakeTorque = .9f * brakes; frontRight.brakeTorque = .9f * brakes; } if (throttle != 0) { //relieve brakes rearLeft.brakeTorque = 0; rearRight.brakeTorque = 0; frontLeft.brakeTorque = 0; frontRight.brakeTorque = 0; } //braking is button x for now if (OVRInput.Get(OVRInput.Button.Three)) { if (car.velocity.z > 1) { rearLeft.brakeTorque = brakes; rearRight.brakeTorque = brakes; //reduce power of front brakes to prevent flipping frontLeft.brakeTorque = .8f * brakes; frontRight.brakeTorque = .8f * brakes; } //else, holding x will reverse else { rearLeft.motorTorque = -force; rearRight.motorTorque = -force; } } if (OVRInput.GetUp(OVRInput.Button.Three)) { rearLeft.brakeTorque = 0; rearRight.brakeTorque = 0; frontLeft.brakeTorque = 0; frontRight.brakeTorque = 0; } }
private void Update() { bool rNearTouch = OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, OVRInput.Controller.RTouch); bool lNearTouch = OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, OVRInput.Controller.LTouch); //Right and left hand Hand Triggers float rPHTrig = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.RTouch); float lPHTrig = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.LTouch); //Right and left hand Index Triggers float rPITrig = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.RTouch); float lPITrig = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger, OVRInput.Controller.LTouch); // TOGGLE FUNCTIONALITY if (OVRInput.GetDown(OVRInput.Button.PrimaryThumbstick, OVRInput.Controller.RTouch)) { //if (!handFunc.isLaser) if (SceneManager.GetActiveScene().name == "OkloVROutdoors_PROPRIETARY" || !handFunc.isLaser) { if (!tooltipOn) { ToolTipActivation(true); } else { ToolTipActivation(false); } } } // RESETTING FUNCTIONAILTY if ((lPITrig == 1 && lPHTrig == 1 && lNearTouch))// && (rPITrig == 1 && rPHTrig == 1 && rNearTouch)) { if (!resetSoundStarted) { aSourceReset.Play(0); resetSoundStarted = true; } resetValueCanvas.gameObject.SetActive(true); float curPct = resetValueCanvas.transform.GetChild(0).GetChild(0).GetComponent <ProgressBar>().currentPercent; curPct += Time.deltaTime / 1.25f * 100f; if (curPct >= 100) { if (!resetHasStarted) { StartCoroutine(DelayReset()); resetValueCanvas.transform.GetChild(0).GetChild(0).GetComponent <ProgressBar>().currentPercent = 100; resetHasStarted = false; } resetValueCanvas.gameObject.SetActive(false); } else { VRButtonFuncs.VibrateTouch(lHand.GetComponent <Collider>()); resetValueCanvas.transform.GetChild(0).GetChild(0).GetComponent <ProgressBar>().currentPercent = curPct; } } else { aSourceReset.Stop(); resetSoundStarted = false; resetValueCanvas.transform.GetChild(0).GetChild(0).GetComponent <ProgressBar>().currentPercent = 0; resetValueCanvas.gameObject.SetActive(false); } }
public virtual void UpdateMovement() { if (HaltUpdateMovement) { return; } if (EnableLinearMovement) { bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); bool dpad_move = false; if (OVRInput.Get(OVRInput.Button.DpadUp)) { moveForward = true; dpad_move = true; } if (OVRInput.Get(OVRInput.Button.DpadDown)) { moveBack = true; dpad_move = true; } MoveScale = 1.0f; if ((moveForward && moveLeft) || (moveForward && moveRight) || (moveBack && moveLeft) || (moveBack && moveRight)) { MoveScale = 0.70710678f; } // No positional movement if we are in the air if (!Controller.isGrounded) { MoveScale = 0.0f; } MoveScale *= SimulationRate * Time.deltaTime; // Compute this for key movement float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; // Run! if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { moveInfluence *= 2.0f; } Quaternion ort = transform.rotation; Vector3 ortEuler = ort.eulerAngles; ortEuler.z = ortEuler.x = 0f; ort = Quaternion.Euler(ortEuler); if (moveForward) { MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward); } if (moveBack) { MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); } if (moveLeft) { MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); } if (moveRight) { MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); } moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad moveInfluence *= 1.0f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger); #endif Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick); // If speed quantization is enabled, adjust the input to the number of fixed speed steps. if (FixedSpeedSteps > 0) { primaryAxis.y = Mathf.Round(primaryAxis.y * FixedSpeedSteps) / FixedSpeedSteps; primaryAxis.x = Mathf.Round(primaryAxis.x * FixedSpeedSteps) / FixedSpeedSteps; } if (primaryAxis.y > 0.0f) { MoveThrottle += ort * (primaryAxis.y * transform.lossyScale.z * moveInfluence * Vector3.forward); } if (primaryAxis.y < 0.0f) { MoveThrottle += ort * (Mathf.Abs(primaryAxis.y) * transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); } if (primaryAxis.x < 0.0f) { MoveThrottle += ort * (Mathf.Abs(primaryAxis.x) * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); } if (primaryAxis.x > 0.0f) { MoveThrottle += ort * (primaryAxis.x * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); } } if (EnableRotation) { Vector3 euler = transform.rotation.eulerAngles; float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier; bool curHatLeft = OVRInput.Get(OVRInput.Button.PrimaryShoulder); if (curHatLeft && !prevHatLeft) { euler.y -= RotationRatchet; } prevHatLeft = curHatLeft; bool curHatRight = OVRInput.Get(OVRInput.Button.SecondaryShoulder); if (curHatRight && !prevHatRight) { euler.y += RotationRatchet; } prevHatRight = curHatRight; euler.y += buttonRotation; buttonRotation = 0f; #if !UNITY_ANDROID || UNITY_EDITOR if (!SkipMouseRotation) { euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f; euler.x -= Input.GetAxis("Mouse Y") * rotateInfluence * 3.25f; } #endif if (SnapRotation) { if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickLeft) || (RotationEitherThumbstick && OVRInput.Get(OVRInput.Button.PrimaryThumbstickLeft))) { if (ReadyToSnapTurn) { euler.y -= RotationRatchet; ReadyToSnapTurn = false; } } else if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickRight) || (RotationEitherThumbstick && OVRInput.Get(OVRInput.Button.PrimaryThumbstickRight))) { if (ReadyToSnapTurn) { euler.y += RotationRatchet; ReadyToSnapTurn = false; } } else { ReadyToSnapTurn = true; } } else { Vector2 secondaryAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick); if (RotationEitherThumbstick) { Vector2 altSecondaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick); if (secondaryAxis.sqrMagnitude < altSecondaryAxis.sqrMagnitude) { secondaryAxis = altSecondaryAxis; } } euler.y += secondaryAxis.x * rotateInfluence; } transform.rotation = Quaternion.Euler(euler); } }
Vector3 previousPointerPos; //using this for velocity since Unity's broken physics engine won't give it to me otherwise // Update is called once per frame void Update() { //Assets/Oculus/VR/Scripts.OVRInput.cs has the button definitions //this helps as well https://developer.oculus.com/documentation/unity/unity-ovrinput/?locale=en_US //Note that the things labelled as "Axis1D" such as triggers can be treated like axes (e.g. input 0-1.0) or like buttons (up or down) //Equivalent to InputAction ShootGun in UE4 version //I'm doing a bunch of else ifs to make it impossible to hit multiple buttons at once if (OVRInput.GetDown(OVRInput.RawButton.LIndexTrigger)) { outputText.text = "Shoot"; if (!thingOnGun) { //Quaternion.lookat functions basically the same way as UE4's MakeRotFromX Bullet spawnedBullet = Instantiate(definitionOfABullet, leftPointerObject.transform.position, Quaternion.LookRotation(leftPointerObject.transform.up)); //you should do a nullity check to make sure it actually has a rigidbody, since in Unity, it's possible for a thing to NOT have physics at all, which is not true for UE4 spawnedBullet.GetComponent <Rigidbody>().AddForce(leftPointerObject.transform.up * 100000); } else { detachGameObject(thingOnGun, AttachmentRule.KeepWorld, AttachmentRule.KeepWorld, AttachmentRule.KeepWorld); simulatePhysics(thingOnGun, Vector3.zero, true); thingOnGun.GetComponent <Rigidbody>().AddForce(leftPointerObject.transform.up * 1000); thingOnGun = null; } } else if (OVRInput.GetUp(OVRInput.RawButton.LIndexTrigger)) { outputText.text = "Release"; } //Equivalent to InputAction GoToThere in UE4 version else if (OVRInput.GetDown(OVRInput.RawButton.RIndexTrigger)) { outputText3.text = "Teleport"; RaycastHit outHit; if (Physics.Raycast(rightPointerObject.transform.position, rightPointerObject.transform.up, out outHit, 100.0f)) { //you can only see these rays when you leave Game window and look at Scene Window. Can't draw rays in-game like in UE4 unless you create your own Ray prefab Debug.DrawRay(rightPointerObject.transform.position, rightPointerObject.transform.up * outHit.distance, Color.red, 10000); outputText2.text = "hit =" + outHit.collider.gameObject; //remember that Unity is Y-up, so I need to swap the axes NavMeshHit navMeshHit; NavMesh.SamplePosition(new Vector3(outHit.point.x, this.gameObject.transform.position.y, outHit.point.z), out navMeshHit, 10, NavMesh.AllAreas); this.gameObject.transform.position = new Vector3(navMeshHit.position.x, this.gameObject.transform.position.y, navMeshHit.position.z); } //equivalent to GrabRight in UE4 version (right grip) } else if (OVRInput.GetDown(OVRInput.RawButton.RHandTrigger)) { outputText3.text = "Grip"; //In Unity, I can't directly get the overlapping actors of a component. I need to query it manually with Physics.OverlapSphere or OnTriggerEnter //I overlap with 1 cm radius to try to get only things near hand //this will also return collider for the hand mesh if there is one. I disabled it but keep it in mind. You need to make sure hand is on a different layer //collectiblesMask is defined at the top right of the Inspector where it says Layer. The layer controls which things to hit (there is no "class filter" like in UE4) Collider[] overlappingThings = Physics.OverlapSphere(rightPointerObject.transform.position, 0.01f, collectiblesMask); if (overlappingThings.Length > 0) { attachGameObjectToAChildGameObject(overlappingThings[0].gameObject, rightPointerObject, AttachmentRule.KeepWorld, AttachmentRule.KeepWorld, AttachmentRule.KeepWorld, true); //I'm not bothering to check for nullity because layer mask should ensure I only collect collectibles. thingIGrabbed = overlappingThings[0].gameObject.GetComponent <Collectible>(); } } else if (OVRInput.GetUp(OVRInput.RawButton.RHandTrigger) || OVRInput.GetUp(OVRInput.RawButton.A) || OVRInput.GetUp(OVRInput.RawButton.B) || OVRInput.GetUp(OVRInput.RawButton.RThumbstick)) { letGo(); //since you can't merge paths the way I did in BP, I need to create a function that does the force grab thing or else I would duplicate code //equivalent to ShootAndGrabNoSnap in UE4 version (A) } else if (OVRInput.GetDown(OVRInput.RawButton.A)) { outputText3.text = "Force Grab at Distance"; forceGrab(true); //equivalent to ShootAndGrabSnap in UE4 version (B) } else if (OVRInput.GetDown(OVRInput.RawButton.B)) { outputText3.text = "Force Grab Snap"; forceGrab(false); //equivalent to MagneticGrip in UE4 version (RS/R3) } else if (OVRInput.GetDown(OVRInput.RawButton.RThumbstick)) { outputText3.text = "Magnetic Grip"; Collider[] overlappingThings = Physics.OverlapSphere(rightPointerObject.transform.position, 1, collectiblesMask); if (overlappingThings.Length > 0) { Collectible nearestCollectible = getClosestHitObject(overlappingThings); attachGameObjectToAChildGameObject(nearestCollectible.gameObject, rightPointerObject, AttachmentRule.SnapToTarget, AttachmentRule.SnapToTarget, AttachmentRule.KeepWorld, true); //I'm not bothering to check for nullity because layer mask should ensure I only collect collectibles. thingIGrabbed = nearestCollectible.gameObject.GetComponent <Collectible>(); } } previousPointerPos = rightPointerObject.gameObject.transform.position; }
// Just checking the state of the index and thumb cap touch sensors, but with a little bit of // debouncing. private void UpdateCapTouchStates() { m_isPointing = !OVRInput.Get(OVRInput.NearTouch.PrimaryIndexTrigger, m_controller); m_isGivingThumbsUp = !OVRInput.Get(OVRInput.NearTouch.PrimaryThumbButtons, m_controller); }
void OnCollisionEnter(Collision col) { if (col.collider.tag == "Player" && (OVRInput.Get(OVRInput.RawButton.RIndexTrigger)) && (OVRInput.Get(OVRInput.RawButton.RHandTrigger)) && OVRInput.Get(OVRInput.RawTouch.B) && OVRInput.Get(OVRInput.RawTouch.A)) { Debug.Log(col.collider.transform.right); //if (lastSphere) //Debug.Log(Vector3.Angle (-(col.collider.transform.right), Vector3.left)); if (lastSphere && (rightHand.transform.rotation.z > 75 || rightHand.transform.rotation.z < 0)) //TODO { Debug.Log("RETURNED"); return; } Simulation_Game_Manager.spheresOnScene -= 1; vibrate(); Destroy(gameObject); } }
/// <summary> /// Gets the position of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerPosition(OVRInput.Controller controllerType) { if (!OVRManager.isHmdPresent) return Vector3.zero; switch (controllerType) { case Controller.LTouch: return GetLocalHandPosition(OVRInput.Hand.Left); case Controller.RTouch: return GetLocalHandPosition(OVRInput.Hand.Right); default: return Vector3.zero; } }
/// <summary> /// Update is called every frame. /// For SteamVR plugin this is where the device Index is set up. /// For Oculus plugin this is where the tracking is done. /// </summary> void Update() { #if ZED_OCULUS //Used only if the Oculus Integration plugin is detected. //Check if the VR headset is connected. if (OVRManager.isHmdPresent && loadeddevice == "Oculus") { if (OVRInput.GetConnectedControllers().ToString() == "Touch") { //Depending on which tracked device we are looking for, start tracking it. if (deviceToTrack == Devices.LeftController) //Track the Left Oculus Controller. { RegisterPosition(1, OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch)); } if (deviceToTrack == Devices.RightController) //Track the Right Oculus Controller. { RegisterPosition(1, OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch)); } if (deviceToTrack == Devices.Hmd) //Track the Oculus Hmd. { RegisterPosition(1, UnityEngine.VR.InputTracking.GetLocalPosition(UnityEngine.VR.VRNode.CenterEye), UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.CenterEye)); } //Use our saved positions to apply a delay before assigning it to this object's Transform. if (poseData.Count > 0) { sl.Pose p; //Delay the saved values inside GetValuePosition() by a factor of latencyCompensation in milliseconds. p = GetValuePosition(1, (float)(latencyCompensation / 1000.0f)); transform.position = p.translation; //Assign new delayed Position transform.rotation = p.rotation; //Assign new delayed Rotation. } } } //Enable updating the internal state of OVRInput. OVRInput.Update(); #endif #if ZED_STEAM_VR lastcontrollerstate = controllerstate; UpdateControllerState(); //Get the button states so we can check if buttons are down or not. timerSteamVR += Time.deltaTime; //Increment timer for checking on devices if (timerSteamVR <= timerMaxSteamVR) { return; } timerSteamVR = 0f; //Checks if a device has been assigned if (index == EIndex.None && loadeddevice == "OpenVR") { if (BIsManufacturerController("HTC") || BIsManufacturerController("Oculus")) { //We look for any device that has "tracker" in its 3D model mesh name. //We're doing this since the device ID changes based on how many devices are connected to SteamVR. //This way, if there's no controllers or just one, it's going to get the right ID for the Tracker. if (deviceToTrack == Devices.ViveTracker) { var error = ETrackedPropertyError.TrackedProp_Success; for (uint i = 0; i < 16; i++) { var result = new System.Text.StringBuilder((int)64); OpenVR.System.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_RenderModelName_String, result, 64, ref error); if (result.ToString().Contains("tracker")) { index = (EIndex)i; break; //We break out of the loop, but we can use this to set up multiple Vive Trackers if we want to. } } } //Looks for a device with the role of a Right Hand. if (deviceToTrack == Devices.RightController) { index = (EIndex)OpenVR.System.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.RightHand); } //Looks for a device with the role of a Left Hand. if (deviceToTrack == Devices.LeftController) { index = (EIndex)OpenVR.System.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.LeftHand); } //Assigns the HMD. if (deviceToTrack == Devices.Hmd) { index = EIndex.Hmd; } } //Display a warning if there was supposed to be a calibration file, and none was found. if (SNHolder.Equals("NONE")) { Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.PAD_CAMERA_CALIBRATION_NOT_FOUND)); } else if (SNHolder != null && index != EIndex.None) // { //If the Serial number of the Calibrated device isn't the same as the current tracked device by this script... //if (!SteamVR.instance.GetStringProperty(Valve.VR.ETrackedDeviceProperty.Prop_SerialNumber_String, (uint)index).Contains(SNHolder) var snerror = ETrackedPropertyError.TrackedProp_Success; var snresult = new System.Text.StringBuilder((int)64); OpenVR.System.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_SerialNumber_String, snresult, 64, ref snerror); if (!snresult.ToString().Contains(SNHolder)) { Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.PAD_CAMERA_CALIBRATION_MISMATCH) + " Serial Number: " + SNHolder); //... then look for that device through all the connected devices. for (int i = 0; i < 16; i++) { //If a device with the same Serial Number is found, then change the device to track of this script. //if(SteamVR.instance.GetStringProperty(Valve.VR.ETrackedDeviceProperty.Prop_SerialNumber_String, (uint)i).Contains(SNHolder)) var chsnresult = new System.Text.StringBuilder((int)64); OpenVR.System.GetStringTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_SerialNumber_String, chsnresult, 64, ref snerror); if (snresult.ToString().Contains(SNHolder)) { index = (EIndex)i; string deviceRole = OpenVR.System.GetControllerRoleForTrackedDeviceIndex((uint)index).ToString(); if (deviceRole.Equals("RightHand")) { deviceToTrack = Devices.RightController; } else if (deviceRole.Equals("LeftHand")) { deviceToTrack = Devices.LeftController; } else if (deviceRole.Equals("Invalid")) { var error = ETrackedPropertyError.TrackedProp_Success; var result = new System.Text.StringBuilder((int)64); OpenVR.System.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, result, 64, ref error); if (result.ToString().Contains("tracker")) { deviceToTrack = Devices.ViveTracker; } } Debug.Log("A connected device with the correct Serial Number was found, and assigned to " + this + " the correct device to track."); break; } } } } oldDevice = deviceToTrack; } if (deviceToTrack != oldDevice) { index = EIndex.None; } #endif }
/// <summary> /// Gets the local Hand position of the given Hand. /// </summary> public static Vector3 GetLocalHandPosition(OVRInput.Hand hand) { if (!OVRManager.instance.isVRPresent) return Vector3.zero; return OVRPlugin.GetNodePose((OVRPlugin.Node)hand+3).ToOVRPose().position; }
/// <summary> /// Update the controller data from the provided platform state /// </summary> /// <param name="interactionSourceState">The InteractionSourceState retrieved from the platform</param> public void UpdateController(OVRInput.Controller ovrController, Transform trackingRoot) { if (!Enabled || trackingRoot == null) { return; } IsPositionAvailable = OVRInput.GetControllerPositionValid(ovrController); IsRotationAvailable = OVRInput.GetControllerOrientationValid(ovrController); // Update transform Vector3 localPosition = OVRInput.GetLocalControllerPosition(ovrController); Vector3 worldPosition = trackingRoot.TransformPoint(localPosition); // Debug.Log("Controller " + Handedness + " - local: " + localPosition + " - world: " + worldPosition); Quaternion localRotation = OVRInput.GetLocalControllerRotation(ovrController); Quaternion worldRotation = trackingRoot.rotation * localRotation; // Update velocity Vector3 localVelocity = OVRInput.GetLocalControllerVelocity(ovrController); Velocity = trackingRoot.TransformDirection(localVelocity); Vector3 localAngularVelocity = OVRInput.GetLocalControllerAngularVelocity(ovrController); AngularVelocity = trackingRoot.TransformDirection(localAngularVelocity); UpdateJointPoses(); // If not rendering avatar hands, pointer pose is not available, so we approximate it if (IsPositionAvailable) { currentPointerPose.Position = currentGripPose.Position = worldPosition; } if (IsRotationAvailable) { currentPointerPose.Rotation = currentGripPose.Rotation = worldRotation; } // Todo: Complete touch controller mapping bool isTriggerPressed = false; bool isGripPressed = false; if (ControllerHandedness == Handedness.Left) { isTriggerPressed = OVRInput.Get(OVRInput.RawAxis1D.LIndexTrigger) > cTriggerDeadZone; isGripPressed = OVRInput.Get(OVRInput.RawAxis1D.LHandTrigger) > cTriggerDeadZone; } else { isTriggerPressed = OVRInput.Get(OVRInput.RawAxis1D.RIndexTrigger) > cTriggerDeadZone; isGripPressed = OVRInput.Get(OVRInput.RawAxis1D.RHandTrigger) > cTriggerDeadZone; } for (int i = 0; i < Interactions?.Length; i++) { switch (Interactions[i].InputType) { case DeviceInputType.SpatialPointer: Interactions[i].PoseData = currentPointerPose; if (Interactions[i].Changed) { CoreServices.InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentPointerPose); } break; case DeviceInputType.SpatialGrip: Interactions[i].PoseData = currentGripPose; if (Interactions[i].Changed) { CoreServices.InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentGripPose); } break; case DeviceInputType.Select: Interactions[i].BoolData = isTriggerPressed || isGripPressed; if (Interactions[i].Changed) { if (Interactions[i].BoolData) { CoreServices.InputSystem?.RaiseOnInputDown(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction); } else { CoreServices.InputSystem?.RaiseOnInputUp(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction); } } break; case DeviceInputType.TriggerPress: Interactions[i].BoolData = isGripPressed || isTriggerPressed; if (Interactions[i].Changed) { if (Interactions[i].BoolData) { CoreServices.InputSystem?.RaiseOnInputDown(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction); } else { CoreServices.InputSystem?.RaiseOnInputUp(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction); } } break; case DeviceInputType.IndexFinger: UpdateIndexFingerData(Interactions[i]); break; } } }
/// <summary> /// Returns true if the given Controller's position is currently tracked. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return false. /// </summary> public static bool GetControllerPositionTracked(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: return OVRPlugin.GetNodePositionTracked(OVRPlugin.Node.HandLeft); case Controller.RTouch: return OVRPlugin.GetNodePositionTracked(OVRPlugin.Node.HandRight); default: return false; } }
public override void OnUpdate() { if (m_localPlayer == null) { VRC.Player player = VRC.Player.prop_Player_0; if (player != null) // early init I guess { m_localPlayer = player; } } if (m_localPlayer == null) { return; // wait until player is ready } var currentInput = VRCInputManager.field_Private_Static_EnumNPublicSealedvaKeMoCoGaViOcViDaWaUnique_0; bool controller = currentInput == InputEnum.Controller; bool vr = currentInput == InputEnum.Oculus || currentInput == InputEnum.Vive; bool desktop = (currentInput == InputEnum.Keyboard || currentInput == InputEnum.Mouse); bool isActiveController = controller && Input.GetKey(KeyCode.JoystickButton5); bool isActiveVr = vr && Input.GetKey((KeyCode)Oculus.LeftThumbstickPress); bool isActiveDesktop = desktop && (Input.GetKey(KeyCode.Mouse4) || Input.GetKey(KeyCode.RightControl)); bool swapSpeedsController = controller && Input.GetKey(KeyCode.JoystickButton9); bool swapSpeedsVr = vr && Input.GetKey((KeyCode)Oculus.AButton); bool swapSpeedsKeyboard = desktop && Input.GetKey(KeyCode.LeftShift); bool isActive = isActiveController || isActiveVr || isActiveDesktop; bool swapSpeeds = swapSpeedsKeyboard || swapSpeedsController || swapSpeedsVr; if (isActive && Time.time - m_lastTime > 1f) { if (m_airbreakActive) { // VRCUiManager.QueueHudMessage equivalent // still same bug as years ago where two messages need to be queued for the first one to be displayed immediately VRCUiManager.prop_VRCUiManager_0.field_Private_List_1_String_0.Add("Noclip OFF"); VRCUiManager.prop_VRCUiManager_0.field_Private_List_1_String_0.Add(""); DisableAirbreak(); } else { VRCUiManager.prop_VRCUiManager_0.field_Private_List_1_String_0.Add("Noclip ON"); VRCUiManager.prop_VRCUiManager_0.field_Private_List_1_String_0.Add(""); SetupAirbreak(); } m_airbreakActive = !m_airbreakActive; m_lastTime = Time.time; } if (swapSpeeds && m_airbreakActive && Time.time - m_lastTime > 0.2f) { m_speedIndex += 1; if (m_speedIndex > m_speeds.Count() - 1) { m_speedIndex = 0; } m_currentSpeed = m_speeds[m_speedIndex]; m_lastTime = Time.time; } // get default fallback Object[] ctrls = Object.FindObjectsOfType(Il2CppType.Of <VRCVrCameraOculus>()); Transform trans = null; if (ctrls.Length > 0) { trans = ctrls[0].TryCast <VRCVrCameraOculus>().transform; } // alright so // let's start by getting our current vrcPlayer VRCPlayer vrcPlayer = m_localPlayer.field_Internal_VRCPlayer_0; Animator animator = null; if (vrcPlayer == null) { animator = null; } else { // let's get our avatar manager VRCAvatarManager vrcAvatarManager = vrcPlayer.prop_VRCAvatarManager_0; if (vrcAvatarManager == null) { animator = null; } else { // current avatar GameObject currentAvatar = vrcAvatarManager.prop_GameObject_0; animator = ((currentAvatar != null) ? currentAvatar.GetComponent(Il2CppType.Of <Animator>())?.TryCast <Animator>() : null); } } // if the animator is not null at this stage and airbreak is enabled if (animator != null) { // get the head bone Transform tempTrans = animator.GetBoneTransform(HumanBodyBones.Head); // if we're humanoid if (tempTrans != null) { // use the head bone's transform instead of oculus camera trans = tempTrans; } } if (trans == null) { MelonLogger.LogError("not humanoid?"); return; } if (Input.GetKey(KeyCode.W)) { m_position += trans.forward * m_currentSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.A)) { m_position += (trans.right * -1) * m_currentSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.S)) { m_position += (trans.forward * -1) * m_currentSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.D)) { m_position += trans.right * m_currentSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.E)) { m_position += m_localPlayer.transform.up * m_currentSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.Q)) { m_position += (m_localPlayer.transform.up * -1) * m_currentSpeed * Time.deltaTime; } var a = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick, OVRInput.Controller.LTouch); if (a.y != 0.0f) { m_position += trans.forward * m_currentSpeed * Time.deltaTime * a.y; } if (a.x != 0.0f) { m_position += trans.right * m_currentSpeed * Time.deltaTime * a.x; } if (m_airbreakActive) { m_localPlayer.transform.position = m_position; } }
/// <summary> /// Gets the angular acceleration of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Quaternion GetLocalControllerAngularAcceleration(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandLeft).ToOVRPose().orientation; case Controller.RTouch: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandRight).ToOVRPose().orientation; default: return Quaternion.identity; } }
/// <summary> /// Returns true if the given Controller's position is currently tracked. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return false. /// </summary> public static bool GetControllerPositionTracked(OVRInput.Controller controllerType) { #if OVR_LEGACY if (!OVRManager.instance.isVRPresent) return false; #else if (!OVRManager.isHmdPresent) return false; #endif switch (controllerType) { case Controller.LTouch: return OVRPlugin.GetNodePositionTracked(OVRPlugin.Node.HandLeft); case Controller.RTouch: return OVRPlugin.GetNodePositionTracked(OVRPlugin.Node.HandRight); default: return false; } }