// Update is called once per frame void Update() { if (controllerIndex == -1) { Debug.LogWarning("Controller not found"); return; } if (!IsControllerStillConnected()) { Debug.LogWarning("Device disconnected"); return; } // Update game object with the position and rotation of the VR controller Vector3 handPosition = InputTracking.GetLocalPosition(vrNode); //Debug.Log("Hand Position = " + handPosition); gameObject.transform.localPosition = handPosition; Quaternion handRotation = InputTracking.GetLocalRotation(vrNode); //Debug.Log("Hand Rotation = " + handRotation); gameObject.transform.localRotation = handRotation; }
void FixedUpdate() //was previously FixedUpdate() { string path = Application.persistentDataPath + "/CW4Test_Data.txt"; // This text is always added, making the file longer over time if it is not deleted string appendText = "\n" + String.Format("{0,20} {1,7} {2, 8} {3, 15} {4, 15} {5, 15} {6, 15} {7, 8} {8, 15} {9, 10} {10, 10} {11, 10} {12, 10} {13, 10} {14, 10} {15, 10} {16, 10}", DateTime.Now.ToString(), Time.time, Input.GetMouseButtonDown(0), Input.gyro.userAcceleration.x, Input.gyro.userAcceleration.y, Input.gyro.userAcceleration.z, gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z, InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.x, InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.y, InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.z, sumY.ToString(), walking.ToString(), wasTwo.ToString(), velocity, decayRate); File.AppendAllText(path, appendText); //Determine if the user is walking, more details inside manageWalking(); //Do the movement algorithm, more details inside move(); //Send the current transform data to the server (should probably be wrapped in an if isAndroid but I haven't tested) if (myClient != null) { myClient.Send(MESSAGE_DATA, new TDMessage(this.transform.localPosition, Camera.main.transform.eulerAngles)); } }
private void Update() { if (!isVRMode) { mainCamera.localRotation = InputTracking.GetLocalRotation(XRNode.CenterEye); } }
/// @endcond private void CastRay() { Quaternion headOrientation; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) headOrientation = InputTracking.GetLocalRotation(VRNode.Head); #else headOrientation = GvrViewer.Instance.HeadPose.Orientation; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Vector2 headPose = NormalizedCartesianToSpherical(headOrientation * Vector3.forward); if (pointerData == null) { pointerData = new PointerEventData(eventSystem); lastHeadPose = headPose; } // Store the previous raycast result. RaycastResult previousRaycastResult = pointerData.pointerCurrentRaycast; // The initial cast must use the enter radius. if (pointer != null) { pointer.ShouldUseExitRadiusForRaycast = false; } // Cast a ray into the scene pointerData.Reset(); pointerData.position = GetPointerPosition(); eventSystem.RaycastAll(pointerData, m_RaycastResultCache); RaycastResult raycastResult = FindFirstRaycast(m_RaycastResultCache); // If we were already pointing at an object we must check that object against the exit radius // to make sure we are no longer pointing at it to prevent flicker. if (previousRaycastResult.gameObject != null && raycastResult.gameObject != previousRaycastResult.gameObject) { if (pointer != null) { pointer.ShouldUseExitRadiusForRaycast = true; } m_RaycastResultCache.Clear(); eventSystem.RaycastAll(pointerData, m_RaycastResultCache); RaycastResult firstResult = FindFirstRaycast(m_RaycastResultCache); if (firstResult.gameObject == previousRaycastResult.gameObject) { raycastResult = firstResult; } } if (raycastResult.gameObject != null && raycastResult.worldPosition == Vector3.zero) { raycastResult.worldPosition = GetIntersectionPosition(pointerData.enterEventCamera, raycastResult); } pointerData.pointerCurrentRaycast = raycastResult; m_RaycastResultCache.Clear(); pointerData.delta = headPose - lastHeadPose; lastHeadPose = headPose; }
/// <summary> /// Return a quaternion for the Y axis of the HMD's orientation. /// Used by orientation handlers to track the current heading before processing user input to adjust it. /// </summary> /// <returns></returns> public Quaternion GetHeadRotationY() { Quaternion headRotation = Quaternion.identity; #if UNITY_2019_1_OR_NEWER UnityEngine.XR.InputDevice device = UnityEngine.XR.InputDevices.GetDeviceAtXRNode(UnityEngine.XR.XRNode.Head); if (device.isValid) { device.TryGetFeatureValue(UnityEngine.XR.CommonUsages.deviceRotation, out headRotation); } #elif UNITY_2017_2_OR_NEWER List <UnityEngine.XR.XRNodeState> nodeStates = new List <UnityEngine.XR.XRNodeState>(); UnityEngine.XR.InputTracking.GetNodeStates(nodeStates); foreach (UnityEngine.XR.XRNodeState n in nodeStates) { if (n.nodeType == UnityEngine.XR.XRNode.Head) { n.TryGetRotation(out headRotation); break; } } #else headRotation = InputTracking.GetLocalRotation(VRNode.Head); #endif Vector3 euler = headRotation.eulerAngles; euler.x = 0; euler.z = 0; headRotation = Quaternion.Euler(euler); return(headRotation); }
//Method that will fire a bullet. private void DoFire(Vector3 projectileOrigin) { Quaternion bulletOrientation; if (ShipType.DESTROYER == type && isLocalPlayer) { if (VRSettings.enabled) { bulletOrientation = InputTracking.GetLocalRotation(VRNode.CenterEye); } else { bulletOrientation = Camera.main.transform.rotation; } } else { bulletOrientation = transform.rotation; } Vector3 bulletOrigin = transform.TransformPoint(projectileOrigin); GameObject bullet = (GameObject)Instantiate(projectilePrefab, bulletOrigin, bulletOrientation); bullet.GetComponent <ProjectileController>().clientMode = isLocalPlayer; Destroy(bullet, 1.5f); }
void Update() { transform.rotation = InputTracking.GetLocalRotation(node); // use local rotation when object is parented to a rotating object // the tracked camera must have the same parent //transform.localRotation = InputTracking.GetLocalRotation(node); }
/// @endcond private void CastRay() { Quaternion headOrientation; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) headOrientation = InputTracking.GetLocalRotation(VRNode.Head); #else headOrientation = GvrViewer.Instance.HeadPose.Orientation; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Vector2 headPose = NormalizedCartesianToSpherical(headOrientation * Vector3.forward); if (pointerData == null) { pointerData = new PointerEventData(eventSystem); lastHeadPose = headPose; } // Cast a ray into the scene pointerData.Reset(); //pointerData.position = GetPointerPosition(); pointerData.position = centerOfScreen; eventSystem.RaycastAll(pointerData, m_RaycastResultCache); RaycastResult raycastResult = FindFirstRaycast(m_RaycastResultCache); if (raycastResult.worldPosition == Vector3.zero) { raycastResult.worldPosition = GetIntersectionPosition(pointerData.enterEventCamera, raycastResult); } pointerData.pointerCurrentRaycast = raycastResult; m_RaycastResultCache.Clear(); pointerData.delta = headPose - lastHeadPose; lastHeadPose = headPose; }
/// <summary> /// Collects the position of the HMD with a timestamp, to be looked up later to correct for latency. /// </summary> public void CollectPose() { if (manager == null) { return; } KeyPose k = new KeyPose(); #if UNITY_2019_1_OR_NEWER InputTracking.GetNodeStates(nodeStates); XRNodeState nodeState = nodeStates.Find(node => node.nodeType == XRNode.Head); nodeState.TryGetRotation(out k.Orientation); nodeState.TryGetPosition(out k.Translation); #else k.Orientation = InputTracking.GetLocalRotation(XRNode.Head); k.Translation = InputTracking.GetLocalPosition(XRNode.Head); #endif if (manager.zedCamera.IsCameraReady) { k.Timestamp = manager.zedCamera.GetCurrentTimeStamp(); if (k.Timestamp >= 0) { dllz_latency_corrector_add_key_pose(ref k.Translation, ref k.Orientation, k.Timestamp); //Poses are handled by the wrapper. } } }
void FixedUpdate() //was previously FixedUpdate() { // send the current transform data to the server (should probably be wrapped in an if isAndroid but I haven't tested) string path = Application.persistentDataPath + "/WIP_looking.txt"; string appendText = "\n" + String.Format("{0,20} {1,7} {2, 15} {3, 15} {4, 15} {5, 15} {6, 15} {7, 8}", DateTime.Now.ToString(), Time.time, display.acceleration.x, display.acceleration.y, display.acceleration.z, InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.x, InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.y, InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.z); File.AppendAllText(path, appendText); // do the movement algorithm, more details inside move(); if (myClient != null) { myClient.Send(MESSAGE_DATA, new TDMessage(this.transform.localPosition, Camera.main.transform.eulerAngles)); } }
void Update() { if (_serverState == ServerState.Lobby) { _sendTimer += Time.deltaTime; if (_sendTimer > _sendRate) { _sendTimer = 0; localPlayerInfo.playerAvatar = Convert.ToBase64String( Serialization.Combine( Serialization.ToBytes(InputTracking.GetLocalPosition(XRNode.RightHand)), Serialization.ToBytes(InputTracking.GetLocalPosition(XRNode.LeftHand)), Serialization.ToBytes(InputTracking.GetLocalPosition(XRNode.Head)), Serialization.ToBytes(InputTracking.GetLocalRotation(XRNode.RightHand)), Serialization.ToBytes(InputTracking.GetLocalRotation(XRNode.LeftHand)), Serialization.ToBytes(InputTracking.GetLocalRotation(XRNode.Head)) )); string playerInfoString = JsonUtility.ToJson(new ClientCommand(ClientCommandType.SetPlayerInfo, JsonUtility.ToJson(localPlayerInfo))); if (playerInfoString != lastPlayerInfo) { BSMultiplayerClient._instance.SendString(playerInfoString); lastPlayerInfo = playerInfoString; } } } }
void Update () { Vector3 headPos = InputTracking.GetLocalPosition(VRNode.Head); Vector3 leftHandPos = InputTracking.GetLocalPosition(VRNode.LeftHand) - headPos; Vector3 rightHandPos = InputTracking.GetLocalPosition(VRNode.RightHand) - headPos; float headAngle = InputTracking.GetLocalRotation(VRNode.Head).eulerAngles.y; float leftHandAngle = Mathf.Rad2Deg * Mathf.Atan2(leftHandPos.x, leftHandPos.z); float rightHandAngle = Mathf.Rad2Deg * Mathf.Atan2(rightHandPos.x, rightHandPos.z); if (headAngle > 180) { headAngle -= 360; } // Calculate body angle float offLeft = angleDiff(leftHandAngle, headAngle); float offRight = angleDiff(rightHandAngle, headAngle); float bodyAngle = headAngle + ((offLeft + offRight) / 2); transform.position = headPos; transform.Rotate(Vector3.up * (bodyAngle - transform.eulerAngles.y)); // Send data to RobotCoordinator robCord.DesiredPositionX = headPos.x; robCord.DesiredPositionZ = headPos.z; robCord.DesiredTheta = normalizedRadian(-bodyAngle); }
private Vector3 GetCurrentEyePositionWS(Camera cam) { Vector3 left = Quaternion.Inverse(InputTracking.GetLocalRotation(XRNode.LeftEye)) * InputTracking.GetLocalPosition(XRNode.LeftEye); Vector3 right = Quaternion.Inverse(InputTracking.GetLocalRotation(XRNode.RightEye)) * InputTracking.GetLocalPosition(XRNode.RightEye); Vector3 leftWorld, rightWorld; Vector3 offset = (left - right) * 0.5f; Matrix4x4 m = cam.cameraToWorldMatrix; leftWorld = m.MultiplyPoint(-offset); rightWorld = m.MultiplyPoint(offset); if (cam.stereoActiveEye == Camera.MonoOrStereoscopicEye.Left) { return(leftWorld); } else if (cam.stereoActiveEye == Camera.MonoOrStereoscopicEye.Right) { return(rightWorld); } else { return(cam.transform.position); } }
// Update is called once per frame void Update() { //Looking for the HMD camera in scene if (!m_CamInitialized) { m_Cam = GameObject.FindGameObjectWithTag("MainCamera"); if (m_Cam != null) { m_CamInitialized = true; } else { Debug.Log("No Camera found!"); } } else { //Check whether the user has rotated the headset or not if (current_Angle != m_Cam.transform.eulerAngles.y) { //If the headset was rotated, rotate roboy transform.RotateAround(m_Cam.transform.localPosition, Vector3.up, m_Cam.transform.eulerAngles.y - current_Angle); } current_Angle = m_Cam.transform.eulerAngles.y; //Move roboy accordingly to headset movement Quaternion headRotation = InputTracking.GetLocalRotation(VRNode.Head); transform.position = m_Cam.transform.position + (headRotation * Vector3.forward) * (-0.3f); } }
private IEnumerator MoveFlyer() { while (m_IsGameRunning) { // Set the target marker position to a point forward of the camera multiplied by the distance from the camera. Quaternion headRotation = InputTracking.GetLocalRotation(VRNode.Head); m_TargetMarker.position = m_Camera.position + (headRotation * Vector3.forward) * m_DistanceFromCamera; // Move the camera container forward. m_CameraContainer.Translate(Vector3.forward * Time.deltaTime * m_Speed); // Move the flyer towards the target marker. m_Flyer.position = Vector3.Lerp(m_Flyer.position, m_TargetMarker.position, m_Damping * (1f - Mathf.Exp(k_ExpDampingCoef * Time.deltaTime))); // Calculate the vector from the target marker to the flyer. Vector3 dist = m_Flyer.position - m_TargetMarker.position; // Base the target markers pitch (x rotation) on the distance in the y axis and it's roll (z rotation) on the distance in the x axis. m_TargetMarker.eulerAngles = new Vector3(dist.y, 0f, dist.x) * k_BankingCoef; // Make the flyer bank towards the marker. m_Flyer.rotation = Quaternion.Lerp(m_Flyer.rotation, m_TargetMarker.rotation, m_Damping * (1f - Mathf.Exp(k_ExpDampingCoef * Time.deltaTime))); // Update the score text. m_CurrentScore.text = "Score: " + SessionData.Score; // Wait until next frame. yield return(null); } }
/// <summary> /// Initialize the ZED's tracking with the current HMD position and HMD-ZED calibration. /// This causes the ZED's internal tracking to start where the HMD is, despite being initialized later than the HMD. /// </summary> /// <returns>Initial offset for the ZED's tracking. </returns> public Pose InitTrackingAR() { if (manager == null) { return(new Pose()); } Transform tmpHMD = transform; #if UNITY_2019_1_OR_NEWER InputTracking.GetNodeStates(nodeStates); XRNodeState nodeState = nodeStates.Find(node => node.nodeType == XRNode.Head); nodeState.TryGetRotation(out Quaternion rot); nodeState.TryGetPosition(out Vector3 pos); Pose hmdTransform = new Pose(pos, rot); #else tmpHMD.position = InputTracking.GetLocalPosition(XRNode.Head); tmpHMD.rotation = InputTracking.GetLocalRotation(XRNode.Head); #endif Quaternion r = Quaternion.identity; Vector3 t = Vector3.zero; Pose const_offset = new Pose(t, r); dllz_drift_corrector_set_calibration_const_offset_transform(ref const_offset); zedCamera.ResetTrackingWithOffset(tmpHMD.rotation, tmpHMD.position, HmdToZEDCalibration.rotation, HmdToZEDCalibration.translation); return(new Pose(tmpHMD.position, tmpHMD.rotation)); }
public static void AutoBlur() { if (camera == null) { Debug.LogError("Error: Camera has not been set. Cannot execute blur.\nHint: try 'PupilImageBlur.camera = GameObject.FindGameObjectWithTag('MainCamera');"); } else { if (refresh == 0) { Debug.LogWarning("Refresh rate not set, defaulting to 10 frames"); refresh = 10; } _frames++; if (_lastRotation != InputTracking.GetLocalRotation(XRNode.Head)) { renderer.material.SetFloat("_Alpha", InputTracking.GetLocalRotation(XRNode.Head).y / _lastRotation.y); } if (_frames >= refresh) { _lastRotation = InputTracking.GetLocalRotation(XRNode.Head); _frames = 0; } } }
/// <summary> /// Before the ZED is ready, lock the quads in front of the cameras as latency correction isn't available yet. /// This allows us to see the loading messages (and other virtual objects if desired) while the ZED is still loading. /// Called by Camera.OnPreRender anytime any camera renders. /// </summary> /// <param name="cam">Cam.</param> public void PreRender(Camera cam) { if (cam == finalLeftEye || cam == finalRightEye) { if ((!manager.IsZEDReady && manager.IsStereoRig)) { #if UNITY_2019_1_OR_NEWER InputTracking.GetNodeStates(nodeStates); XRNodeState nodeState = nodeStates.Find(node => node.nodeType == XRNode.Head); nodeState.TryGetRotation(out Quaternion rot); nodeState.TryGetPosition(out Vector3 pos); quadLeft.localRotation = rot; quadLeft.localPosition = pos + quadLeft.localRotation * offset; quadRight.localRotation = rot; quadRight.localPosition = pos + quadRight.localRotation * offset; #else quadLeft.localRotation = InputTracking.GetLocalRotation(XRNode.Head); quadLeft.localPosition = InputTracking.GetLocalPosition(XRNode.Head) + quadLeft.localRotation * offset; quadRight.localRotation = InputTracking.GetLocalRotation(XRNode.Head); quadRight.localPosition = InputTracking.GetLocalPosition(XRNode.Head) + quadRight.localRotation * offset; #endif } } }
private void VRControl() { //本体 if (!XRDevice.isPresent) { Debug.LogWarning("デバイスが接続されていません"); } else { Position = InputTracking.GetLocalPosition(XRNode.CenterEye); Rotation = InputTracking.GetLocalRotation(XRNode.CenterEye); } //OVRInput.Controller c = OVRInput.GetConnectedControllers(); //右手(セカンドトリガー) //if (c != OVRInput.Controller.RTrackedRemote) //{ // Debug.LogWarning("右コントローラーが接続されていません"); //} //else //{ UpdateRController(RC); //} //左手(プライマリトリガー) //if (c != OVRInput.Controller.LTrackedRemote) //{ // Debug.LogWarning("左コントローラーが接続されていません"); //} //else //{ UpdateLController(LC); //} }
void Update() { // For walking action, keep track of what the last pad clicked was so that movement only occurs with alternate clicks // Shouldn't really be in this class which ideally would be restricted to managing the input only if (Input.GetButton("LeftPadDown") && !Input.GetButton("RightPadDown") && !lastClickLeft) { lastClickLeft = true; padClicked.Invoke(); } if (Input.GetButton("RightPadDown") && !Input.GetButton("LeftPadDown") && lastClickLeft) { lastClickLeft = false; padClicked.Invoke(); } if (debugMode) { Vector3 leftPosition = InputTracking.GetLocalPosition(XRNode.LeftHand); Quaternion leftRotation = InputTracking.GetLocalRotation(XRNode.LeftHand); Vector3 rightPosition = InputTracking.GetLocalPosition(XRNode.RightHand); Quaternion rightRotation = InputTracking.GetLocalRotation(XRNode.RightHand); HUDDebug.AddMessage("Left Position: " + leftPosition + " Left Rotation: " + leftRotation); HUDDebug.AddMessage("Right Position: " + rightPosition + " Right Rotation: " + rightRotation); } // Debug.Log(leftPosition + " " + leftRotation + " " + rightPosition + " " + leftHorz); //var interactionSourceStates = InteractionManager.GetCurrentReading(); //Debug.Log(interactionSourceStates); }
/// @endcond private void CastRayFromGaze() { Quaternion headOrientation; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) headOrientation = InputTracking.GetLocalRotation(XRNode.Head); #else headOrientation = GvrViewer.Instance.HeadPose.Orientation; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Vector2 headPose = NormalizedCartesianToSpherical(headOrientation * Vector3.forward); if (pointerData == null) { pointerData = new PointerEventData(eventSystem); lastHeadPose = headPose; } // Cast a ray into the scene pointerData.Reset(); pointerData.position = GetGazePointerPosition(); eventSystem.RaycastAll(pointerData, m_RaycastResultCache); pointerData.pointerCurrentRaycast = FindFirstRaycast(m_RaycastResultCache); m_RaycastResultCache.Clear(); pointerData.delta = headPose - lastHeadPose; lastHeadPose = headPose; }
private void updateTemporalWarping() { if (_trackingAnchor == null) { return; } Vector3 currCenterPos = _trackingAnchor.TransformPoint(InputTracking.GetLocalPosition(VRNode.CenterEye)); Quaternion currCenterRot = _trackingAnchor.rotation * InputTracking.GetLocalRotation(VRNode.CenterEye); //Get the transform at the time when the latest image was captured long rewindTime = HandController.Main.GetFrame().Timestamp; TransformData past = transformAtTime(rewindTime); Vector3 pastCenterPos = _trackingAnchor.TransformPoint(past.localPosition); Quaternion pastCenterRot = _trackingAnchor.rotation * past.localRotation; //Apply only a rotation ~ assume all objects are infinitely distant Quaternion referenceRotation = Quaternion.Slerp(currCenterRot, pastCenterRot, tweenImageWarping); Quaternion quatWarp = Quaternion.Inverse(currCenterRot) * referenceRotation; Matrix4x4 matWarp = _projectionMatrix * Matrix4x4.TRS(Vector3.zero, quatWarp, Vector3.one) * _projectionMatrix.inverse; Shader.SetGlobalMatrix("_LeapGlobalWarpedOffset", matWarp); transform.position = Vector3.Lerp(currCenterPos, pastCenterPos, tweenPositionalWarping); transform.rotation = Quaternion.Slerp(currCenterRot, pastCenterRot, tweenRotationalWarping); transform.position += transform.forward * deviceInfo.focalPlaneOffset; }
public static Quaternion GetHeadRotation() { #if UNITY_EDITOR if (InstantPreview.Instance != null && InstantPreview.Instance.IsCurrentlyConnected) { // In-editor; Instant Preview is active: return(Camera.main.transform.localRotation); } else { // In-editor; Instant Preview is not active: if (GvrEditorEmulator.Instance == null) { Debug.LogWarning("No GvrEditorEmulator instance was found in your scene. Please ensure that " + "GvrEditorEmulator exists in your scene."); return(Quaternion.identity); } return(GvrEditorEmulator.Instance.HeadRotation); } #else // Not running in editor: return(InputTracking.GetLocalRotation(XRNode.Head)); #endif // UNITY_EDITOR }
protected void HandleInputAxes() { //Input.GetAxisRaw returns a value -1, 0, or 1 //float x = Input.GetAxisRaw("Horizontal") * Time.deltaTime; //multiply by Time.deltaTime to normalize movement //float z = Input.GetAxisRaw("Vertical") * Time.deltaTime; //If we're moving, let's tell the player to move if (Input.GetKey(KeyCode.UpArrow)) { yaw = InputTracking.GetLocalRotation(XRNode.Head).eulerAngles.y; rad = yaw * Mathf.Deg2Rad; float z = Mathf.Cos(rad) * Time.deltaTime; float x = Mathf.Sin(rad) * Time.deltaTime; Player.Move(x * 10, z * 10); float newZ = ((Player.transform.position.z + 50) * 1 / 5) + 85; star.rectTransform.localPosition = new Vector3( (Player.transform.position.x * 6 / 16) - 2, newZ - 4, (float)134.2 ); pizzaCarLabel.rectTransform.localPosition = new Vector3( (Player.transform.position.x * 6 / 16), newZ, (float)134.2 ); } }
void Update() { for (int i = 0; i < 2; ++i) { // If the eye anchor is no longer a child of us, don't use it if (eyes[i] != null && eyes[i].transform.parent != transform) { eyes[i] = null; } // If we don't have an eye anchor, try to find one or create one if (eyes[i] == null) { Transform t = transform.Find(eyeAnchorNames[i]); if (t) { eyes[i] = t.gameObject; } if (eyes[i] == null) { eyes[i] = new GameObject(eyeAnchorNames[i]); eyes[i].transform.parent = gameObject.transform; } } // Update the eye transform eyes[i].transform.localPosition = InputTracking.GetLocalPosition((XRNode)i); eyes[i].transform.localRotation = InputTracking.GetLocalRotation((XRNode)i); } }
void Update() { corsurePositio = transform.position; //tempPositio = transform.position; corsurePositio = InputTracking.GetLocalPosition(XRNode.RightHand); corsureRotatio.x = InputTracking.GetLocalRotation(XRNode.RightHand).eulerAngles.x; corsureRotatio.y = InputTracking.GetLocalRotation(XRNode.RightHand).eulerAngles.y; corsureRotatio.z = InputTracking.GetLocalRotation(XRNode.RightHand).eulerAngles.z; //corsureRotatio.x += 30f; Vector3 forwardVector = Quaternion.Euler(corsureRotatio) * Vector3.forward; //Debug.Log(string.Format(" corsureRotation: ") + corsureRotation.x +" , "+ corsureRotation.y + " , " + corsureRotation.z); //currentPositio = corsurePositio + tempPositio; Debug.Log(string.Format(" corsurePosition: ") + corsurePositio + " tempPosition: " + tempPositio + " currentPosition: " + currentPositio); transform.position = corsurePositio;// + new Vector3(0.5f, -1, 0); transform.rotation = Quaternion.Euler(corsureRotatio); //tempPositio = corsurePositio + new Vector3(0.5f, -1, 0); LineRenderer lineRenderer = GetComponent <LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, forwardVector * 15 + transform.position); //transform.position = corsurePosition + one; }
// Update is called once per frame void Update() { timeElapsed += Time.deltaTime; Vector3 cameraPos = Camera.transform.position; Vector3 cameraDir = Camera.transform.forward; Vector3 vrPos = InputTracking.GetLocalPosition(XRNode.CenterEye); Quaternion vrRot = InputTracking.GetLocalRotation(XRNode.CenterEye); Vector3 pos = cameraPos + vrPos; // 視点 Vector3 dir = vrRot * Sword.transform.position; // 方向 Vector3 sworder = dir - pos; var diff = Sword.transform.position - this.transform.position; var axis = Vector3.Cross(this.transform.forward, diff); var angle = Vector3.Angle(this.transform.forward, diff) * (axis.y < 0 ? -1 : 1); NewPos = angle; // each frame track the new position ObjVelocity = NewPos - PrevPos; // velocity = dist/time / Time.deltaTime PrevPos = NewPos; // update position for next frame calculation NewPos2 = Sword.transform.position.y; ObjVelocity2 = NewPos2 - PrevPos2; PrevPos2 = NewPos2; //Debug.Log("YO" + ObjVelocity2); }
private void step() { switch (input_device_type) { // Analog stick (e.g. for conventional console controllers) case InputDevice.DualAxis: Debug.LogError("Not Implemented"); // TODO: implement break; // Motion controllers (e.g. virtual reality) case InputDevice.Gyroscope: // FIXME: the VR tracker goes twice as far as it should; while this is graphically appealing, it has the drawback of being a bug when you get to rotations greater than PI/2 internal_transform.rotation = camera_transform.rotation * InputTracking.GetLocalRotation(virtual_reality_tracker_type); // FIXME: HACK: break; // Computer mouse case InputDevice.Mouse: internal_transform.rotation = Quaternion.LookRotation(internal_camera.ScreenPointToRay(Input.mousePosition).direction, camera_transform.up); break; // Touch devices (e.g. laptops and tablets) case InputDevice.Touchpad: Debug.LogError("Not Implemented"); // TODO: implement break; // Touch devices (e.g. laptops and tablets) case InputDevice.Touchscreen: if (Input.touches.Length > 0) { internal_transform.rotation = Quaternion.LookRotation(internal_camera.ScreenPointToRay(Input.touches[0].position).direction, camera_transform.up); } break; } }
public static Quaternion GetXRNodeLocalRotation(int node) { #if SVR if (SvrManager.Instance != null) { Debug.LogWarning("Not implemented yet"); return(Quaternion.identity); } #endif #if UNITY_2019_2_OR_NEWER InputTracking.GetNodeStates(nodeStates); Quaternion rotation; foreach (XRNodeState state in nodeStates) { if (state.nodeType == (XRNode)node && state.TryGetRotation(out rotation)) { return(rotation); } } return(Quaternion.identity); #elif UNITY_2017_2_OR_NEWER return(InputTracking.GetLocalRotation((XRNode)node)); #else return(InputTracking.GetLocalRotation((VRNode)node)); #endif }
public void UpdateHandPositions() { InventoryItem heldItem = Inventory.main.quickSlots.heldItem; rightController.transform.localPosition = InputTracking.GetLocalPosition(VRNode.RightHand) + new Vector3(0f, -0.13f, -0.14f); rightController.transform.localRotation = InputTracking.GetLocalRotation(VRNode.RightHand) * Quaternion.Euler(35f, 190f, 270f); leftController.transform.localPosition = InputTracking.GetLocalPosition(VRNode.LeftHand) + new Vector3(0f, -0.13f, -0.14f); leftController.transform.localRotation = InputTracking.GetLocalRotation(VRNode.LeftHand) * Quaternion.Euler(270f, 90f, 0f); if (heldItem.item.GetComponent <PropulsionCannon>()) { ik.solver.leftHandEffector.target = null; ik.solver.rightHandEffector.target = null; } else if (heldItem.item.GetComponent <StasisRifle>()) { ik.solver.leftHandEffector.target = null; ik.solver.rightHandEffector.target = null; } else { ik.solver.leftHandEffector.target = leftController.transform; ik.solver.rightHandEffector.target = rightController.transform; } }