SimpleCameraController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEngine.InputSystem;
  5. using UnityEngine.InputSystem.EnhancedTouch;
  6. using EnhancedTouch = UnityEngine.InputSystem.EnhancedTouch.Touch;
  7. using Gyroscope = UnityEngine.InputSystem.Gyroscope;
  8. #if URS_USE_AR_SUBSYSTEMS
  9. using UnityEngine.XR.ARSubsystems;
  10. #endif
  11. namespace Unity.RenderStreaming.Samples
  12. {
  13. using UnityInputSystem = UnityEngine.InputSystem.InputSystem;
  14. static class TouchScreenExtension
  15. {
  16. public static IEnumerable<EnhancedTouch> GetTouches(this Touchscreen screen)
  17. {
  18. return EnhancedTouch.activeTouches.Where(touch => touch.screen == screen);
  19. }
  20. }
  21. [RequireComponent(typeof(InputChannelReceiverBase))]
  22. class SimpleCameraController : MonoBehaviour
  23. {
  24. class CameraState
  25. {
  26. public float yaw;
  27. public float pitch;
  28. public float roll;
  29. public float x;
  30. public float y;
  31. public float z;
  32. public void SetFromTransform(Transform t)
  33. {
  34. pitch = t.eulerAngles.x;
  35. yaw = t.eulerAngles.y;
  36. roll = t.eulerAngles.z;
  37. x = t.position.x;
  38. y = t.position.y;
  39. z = t.position.z;
  40. }
  41. public void Translate(Vector3 translation)
  42. {
  43. Vector3 rotatedTranslation = Quaternion.Euler(pitch, yaw, roll) * translation;
  44. x += rotatedTranslation.x;
  45. y += rotatedTranslation.y;
  46. z += rotatedTranslation.z;
  47. }
  48. public void LerpTowards(CameraState target, float positionLerpPct, float rotationLerpPct)
  49. {
  50. yaw = Mathf.Lerp(yaw, target.yaw, rotationLerpPct);
  51. pitch = Mathf.Lerp(pitch, target.pitch, rotationLerpPct);
  52. roll = Mathf.Lerp(roll, target.roll, rotationLerpPct);
  53. x = Mathf.Lerp(x, target.x, positionLerpPct);
  54. y = Mathf.Lerp(y, target.y, positionLerpPct);
  55. z = Mathf.Lerp(z, target.z, positionLerpPct);
  56. }
  57. public void UpdateTransform(Transform t)
  58. {
  59. t.eulerAngles = new Vector3(pitch, yaw, roll);
  60. t.position = new Vector3(x, y, z);
  61. }
  62. }
  63. [Header("Movement Settings")]
  64. [Tooltip("Movement Sensitivity Factor."), Range(0.001f, 1f)]
  65. [SerializeField] float m_movementSensitivityFactor = 0.1f;
  66. [Tooltip("Exponential boost factor on translation, controllable by mouse wheel.")]
  67. [SerializeField]
  68. private float boost = 3.5f;
  69. [Tooltip("Time it takes to interpolate camera position 99% of the way to the target."), Range(0.001f, 1f)]
  70. [SerializeField]
  71. private float positionLerpTime = 0.2f;
  72. [Header("Rotation Settings")]
  73. [Tooltip("X = Change in mouse position.\nY = Multiplicative factor for camera rotation.")]
  74. [SerializeField]
  75. private AnimationCurve mouseSensitivityCurve = new AnimationCurve(new Keyframe(0f, 0.5f, 0f, 5f), new Keyframe(1f, 2.5f, 0f, 0f));
  76. [Tooltip("Time it takes to interpolate camera rotation 99% of the way to the target."), Range(0.001f, 1f)]
  77. [SerializeField]
  78. private float rotationLerpTime = 0.01f;
  79. [Tooltip("Whether or not to invert our Y axis for mouse input to rotation.")]
  80. [SerializeField]
  81. private bool invertY = false;
  82. [Tooltip("Instance for controlling UI that renders to the camera.")]
  83. [SerializeField]
  84. private UIController uiController = null;
  85. [SerializeField] private InputChannelReceiverBase receiver;
  86. readonly CameraState m_TargetCameraState = new CameraState();
  87. readonly CameraState m_InterpolatingCameraState = new CameraState();
  88. readonly CameraState m_InitialCameraState = new CameraState();
  89. private List<Gamepad> listGamepad = new List<Gamepad>();
  90. private List<Keyboard> listKeyboard = new List<Keyboard>();
  91. private List<Mouse> listMouse = new List<Mouse>();
  92. private List<Gyroscope> listGyroscpe = new List<Gyroscope>();
  93. private List<TrackedDevice> listTracker = new List<TrackedDevice>();
  94. private List<Touchscreen> listScreen = new List<Touchscreen>();
  95. #if URS_USE_AR_SUBSYSTEMS
  96. private List<HandheldARInputDevice> listHandheld = new List<HandheldARInputDevice>();
  97. #endif
  98. void Awake()
  99. {
  100. if (receiver == null)
  101. receiver = GetComponent<InputChannelReceiverBase>();
  102. receiver.onDeviceChange += OnDeviceChange;
  103. EnhancedTouchSupport.Enable();
  104. }
  105. void OnDeviceChange(InputDevice device, InputDeviceChange change)
  106. {
  107. switch (change)
  108. {
  109. case InputDeviceChange.Added:
  110. SetDevice(device);
  111. return;
  112. case InputDeviceChange.Removed:
  113. SetDevice(device, false);
  114. return;
  115. }
  116. }
  117. void SetDevice(InputDevice device, bool add=true)
  118. {
  119. uiController?.SetDevice(device, add);
  120. switch (device)
  121. {
  122. case Mouse mouse:
  123. if (add)
  124. listMouse.Add(mouse);
  125. else
  126. listMouse.Remove(mouse);
  127. return;
  128. case Keyboard keyboard:
  129. if (add)
  130. listKeyboard.Add(keyboard);
  131. else
  132. listKeyboard.Remove(keyboard);
  133. return;
  134. case Touchscreen screen:
  135. if(add)
  136. listScreen.Add(screen);
  137. else
  138. listScreen.Remove(screen);
  139. return;
  140. case Gamepad pad:
  141. if(add)
  142. listGamepad.Add(pad);
  143. else
  144. listGamepad.Remove(pad);
  145. return;
  146. case Gyroscope gyroscope:
  147. if (add)
  148. listGyroscpe.Add(gyroscope);
  149. else
  150. listGyroscpe.Remove(gyroscope);
  151. return;
  152. case TrackedDevice tracker:
  153. if (add)
  154. listTracker.Add(tracker);
  155. else
  156. listTracker.Remove(tracker);
  157. return;
  158. #if URS_USE_AR_SUBSYSTEMS
  159. case HandheldARInputDevice handheld:
  160. if (add)
  161. listHandheld.Add(handheld);
  162. else
  163. listHandheld.Remove(handheld);
  164. return;
  165. #endif
  166. }
  167. }
  168. void OnEnable()
  169. {
  170. m_TargetCameraState.SetFromTransform(transform);
  171. m_InterpolatingCameraState.SetFromTransform(transform);
  172. }
  173. //---------------------------------------------------------------------------------------------------------------------
  174. Vector3 GetTranslationFromInput(Vector2 input) {
  175. if (!invertY) {
  176. input.y *= -1;
  177. }
  178. Vector3 dir = Vector3.right * input.x * m_movementSensitivityFactor;
  179. dir += Vector3.back * input.y * m_movementSensitivityFactor;
  180. return dir;
  181. }
  182. //---------------------------------------------------------------------------------------------------------------------
  183. void UpdateTargetCameraStateFromInput(Vector2 input)
  184. {
  185. if (!invertY) {
  186. input.y *= -1;
  187. }
  188. float mouseSensitivityFactor = mouseSensitivityCurve.Evaluate(input.magnitude);
  189. m_TargetCameraState.yaw += input.x * mouseSensitivityFactor;
  190. m_TargetCameraState.pitch += input.y * mouseSensitivityFactor;
  191. }
  192. //---------------------------------------------------------------------------------------------------------------------
  193. Vector3 GetInputTranslationDirection()
  194. {
  195. Vector3 direction = new Vector3();
  196. // keyboard control
  197. foreach (var keyboard in listKeyboard)
  198. {
  199. if (keyboard.wKey.isPressed)
  200. {
  201. direction += Vector3.forward;
  202. }
  203. if (keyboard.sKey.isPressed)
  204. {
  205. direction += Vector3.back;
  206. }
  207. if (keyboard.aKey.isPressed)
  208. {
  209. direction += Vector3.left;
  210. }
  211. if (keyboard.dKey.isPressed)
  212. {
  213. direction += Vector3.right;
  214. }
  215. if (keyboard.qKey.isPressed)
  216. {
  217. direction += Vector3.down;
  218. }
  219. if (keyboard.eKey.isPressed)
  220. {
  221. direction += Vector3.up;
  222. }
  223. // Speed up movement when shift key held
  224. if (keyboard.leftShiftKey.isPressed)
  225. {
  226. direction *= 10.0f;
  227. }
  228. }
  229. // gamepad right stick control
  230. foreach (var gamepad in listGamepad)
  231. {
  232. if (gamepad?.rightStick != null)
  233. {
  234. var axis = gamepad.rightStick.ReadValue();
  235. direction += new Vector3(axis.x, 0, axis.y);
  236. }
  237. }
  238. // touch
  239. foreach (var screen in listScreen)
  240. {
  241. var touches = screen.GetTouches();
  242. //Translation
  243. if (touches?.Count() == 2)
  244. {
  245. var activeTouches = touches.ToArray();
  246. direction = GetTranslationFromInput((activeTouches[0].delta + activeTouches[1].delta) / 2f);
  247. }
  248. }
  249. // mouse
  250. foreach (var mouse in listMouse)
  251. {
  252. if (IsMouseDragged(mouse, true))
  253. {
  254. direction = GetTranslationFromInput(mouse.delta.ReadValue());
  255. }
  256. }
  257. return direction;
  258. }
  259. void FixedUpdate()
  260. {
  261. foreach (var keyboard in listKeyboard)
  262. {
  263. if (keyboard.uKey.isPressed)
  264. {
  265. ResetCamera();
  266. return;
  267. }
  268. }
  269. foreach (var tracker in listTracker)
  270. {
  271. if (tracker != null && tracker.enabled)
  272. {
  273. m_TargetCameraState.UpdateTransform(transform);
  274. transform.position += tracker.devicePosition.ReadValue();
  275. transform.eulerAngles += tracker.deviceRotation.ReadValue().eulerAngles;
  276. return;
  277. }
  278. }
  279. #if URS_USE_AR_SUBSYSTEMS
  280. foreach(var handheld in listHandheld)
  281. {
  282. if (handheld != null && handheld.enabled)
  283. {
  284. m_TargetCameraState.UpdateTransform(transform);
  285. transform.position += handheld.devicePosition.ReadValue();
  286. transform.eulerAngles += handheld.deviceRotation.ReadValue().eulerAngles;
  287. return;
  288. }
  289. }
  290. #endif
  291. // Rotation
  292. foreach (var mouse in listMouse)
  293. {
  294. if (IsMouseDragged(mouse, false))
  295. {
  296. UpdateTargetCameraStateFromInput(mouse.delta.ReadValue());
  297. }
  298. }
  299. foreach (var screen in listScreen)
  300. {
  301. var touches = screen.GetTouches();
  302. if (touches.Count() == 1)
  303. {
  304. var activeTouches = touches.ToArray();
  305. UpdateTargetCameraStateFromInput(activeTouches[0].delta);
  306. }
  307. }
  308. foreach (var gyroscope in listGyroscpe)
  309. {
  310. if (gyroscope != null && gyroscope.enabled)
  311. {
  312. var v = gyroscope.angularVelocity.ReadValue();
  313. m_TargetCameraState.yaw += v.x;
  314. m_TargetCameraState.pitch -= v.y;
  315. m_TargetCameraState.roll += v.z;
  316. }
  317. }
  318. // Rotation from joystick
  319. foreach (var gamepad in listGamepad)
  320. {
  321. if (gamepad.leftStick != null)
  322. UpdateTargetCameraStateFromInput(gamepad.leftStick.ReadValue());
  323. }
  324. // Translation
  325. var translation = GetInputTranslationDirection() * Time.deltaTime;
  326. translation *= Mathf.Pow(2.0f, boost);
  327. m_TargetCameraState.Translate(translation);
  328. // Framerate-independent interpolation
  329. // Calculate the lerp amount, such that we get 99% of the way to our target in the specified time
  330. var positionLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / positionLerpTime) * Time.deltaTime);
  331. var rotationLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / rotationLerpTime) * Time.deltaTime);
  332. m_InterpolatingCameraState.LerpTowards(m_TargetCameraState, positionLerpPct, rotationLerpPct);
  333. m_InterpolatingCameraState.UpdateTransform(transform);
  334. }
  335. void ResetCamera()
  336. {
  337. m_InitialCameraState.UpdateTransform(transform);
  338. m_TargetCameraState.SetFromTransform(transform);
  339. m_InterpolatingCameraState.SetFromTransform(transform);
  340. }
  341. //---------------------------------------------------------------------------------------------------------------------
  342. static bool IsMouseDragged(Mouse m, bool useLeftButton) {
  343. if (null == m)
  344. return false;
  345. if (Screen.safeArea.Contains(m.position.ReadValue())) {
  346. //check left/right click
  347. if ((useLeftButton && m.leftButton.isPressed) || (!useLeftButton && m.rightButton.isPressed)) {
  348. return true;
  349. }
  350. }
  351. return false;
  352. }
  353. }
  354. }