OffsetCenter.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using UnityEngine;
  2. using System.Collections;
  3. public class OffsetCenter : MonoBehaviour {
  4. /// Offset projection for 2 cameras in VR
  5. public float offset =0.0f;
  6. public float max_offset=0.002f;
  7. public Camera cameraleft;
  8. public Camera cameraright;
  9. private float correctionfactor;
  10. public static OffsetCenter instance;
  11. public bool autoCorrectOffset=true;
  12. private bool debugMetrics=false;
  13. private int vpixels;
  14. private int hpixels;
  15. private float ydpi;
  16. private float xdpi;
  17. private float xmm;
  18. private float ymm;
  19. private float mmdist;
  20. private float correction_factor = 0.0f;
  21. public void Start(){
  22. // Screen Metrics
  23. float dpi = Screen.dpi;
  24. Debug.Log (dpi);
  25. if(dpi <=0){
  26. dpi = 1;
  27. }
  28. vpixels=Screen.height;
  29. hpixels=Screen.width;
  30. xmm=hpixels/Screen.dpi/0.0393701f;
  31. ymm=vpixels/Screen.dpi/0.0393701f;
  32. mmdist = xmm / 2;
  33. }
  34. public void Update () {
  35. correction_factor=0.002f*((mmdist-55.0f)/(76.0f-55.0f));
  36. #if UNITY_EDITOR
  37. #elif UNITY_ANDROID
  38. if (autoCorrectOffset) {
  39. setCorrectionFactor(correction_factor);
  40. }
  41. #endif
  42. }
  43. private void SetVanishingPoint (Camera cam, Vector2 perspectiveOffset) {
  44. Matrix4x4 m = cam.projectionMatrix;
  45. float w = 2*cam.nearClipPlane/m.m00;
  46. float h = 2*cam.nearClipPlane/m.m11;
  47. float left = -w/2 - perspectiveOffset.x;
  48. float right = left+w;
  49. float bottom = -h/2 - perspectiveOffset.y;
  50. float top = bottom+h;
  51. cam.projectionMatrix = PerspectiveOffCenter(left, right, bottom, top, cam.nearClipPlane, cam.farClipPlane);
  52. }
  53. private static Matrix4x4 PerspectiveOffCenter (float left, float right, float bottom, float top, float near, float far)
  54. {
  55. float x = (2.0f * near) / (right - left);
  56. float y = (2.0f * near) / (top - bottom);
  57. float a = (right + left) / (right - left);
  58. float b = (top + bottom) / (top - bottom);
  59. float c = -(far + near) / (far - near);
  60. float d = -(2.0f * far * near) / (far - near);
  61. float e = -1.0f;
  62. Matrix4x4 m = new Matrix4x4();
  63. m[0,0] = x; m[0,1] = 0.0f; m[0,2] = a; m[0,3] = 0.0f;
  64. m[1,0] = 0.0f; m[1,1] = y; m[1,2] = b; m[1,3] = 0.0f;
  65. m[2,0] = 0.0f; m[2,1] = 0.0f; m[2,2] = c; m[2,3] = d;
  66. m[3,0] = 0.0f; m[3,1] = 0.0f; m[3,2] = e; m[3,3] = 0.0f;
  67. return m;
  68. }
  69. public void setCorrectionFactor(float fac){
  70. //offset=max_offset*fac;
  71. offset = fac * 10;
  72. correctionfactor=fac;
  73. Debug.Log (offset);
  74. SetVanishingPoint(cameraleft, new Vector2(offset, 0.0f));
  75. SetVanishingPoint(cameraright, new Vector2(-offset, 0.0f));
  76. }
  77. }