ResetPositionViaTransforms.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using UnityEngine;
  2. namespace ResetPlayerPosition
  3. {
  4. public class ResetPositionViaTransforms : MonoBehaviour
  5. {
  6. [Tooltip("Desired head position of player when seated")]
  7. public Transform desiredHeadPosition;
  8. //Assign these variables in the inspector, or find them some other way (eg. in Start() )
  9. public Transform steamCamera;
  10. public Transform cameraRig;
  11. private void Update()
  12. {
  13. if (Input.GetKeyDown(KeyCode.Space))
  14. {
  15. if (desiredHeadPosition != null)
  16. {
  17. ResetSeatedPos(desiredHeadPosition);
  18. }
  19. else
  20. {
  21. Debug.LogError("Target Transform required. Assign in inspector.", gameObject);
  22. }
  23. }
  24. }
  25. private void ResetSeatedPos(Transform desiredHeadPos)
  26. {
  27. if ((steamCamera != null) && (cameraRig != null))
  28. {
  29. //ROTATION
  30. // Get current head heading in scene (y-only, to avoid tilting the floor)
  31. float offsetAngle = steamCamera.rotation.eulerAngles.y;
  32. // Now rotate CameraRig in opposite direction to compensate
  33. cameraRig.Rotate(0f, -offsetAngle, 0f);
  34. //POSITION
  35. // Calculate postional offset between CameraRig and Camera
  36. Vector3 offsetPos = steamCamera.position - cameraRig.position;
  37. // Reposition CameraRig to desired position minus offset
  38. cameraRig.position = (desiredHeadPos.position - offsetPos);
  39. Debug.Log("Seat recentered!");
  40. }
  41. else
  42. {
  43. Debug.Log("Error: SteamVR objects not found!");
  44. }
  45. }
  46. }
  47. }