CameraLookAround.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /// <summary>
  2. /// Copyright (c) 2021 MirzkisD1Ex0 All rights reserved.
  3. /// Code Version 1.0
  4. /// </summary>
  5. using UnityEngine;
  6. using ToneTuneToolkit.Common;
  7. namespace ToneTuneToolkit.View
  8. {
  9. /// <summary>
  10. /// 鼠标拖动控制相机旋转
  11. ///
  12. /// 推荐挂在相机上
  13. /// 需要设置MainCameraTag
  14. /// 如果是为了实现全景效果,建议减少球模型的面数,此外还需要在建模软件内将模型的法线翻转至球的内侧
  15. /// 或者使用Sphere + Panoramic材质 // 更省事
  16. /// </summary>
  17. public class CameraLookAround : MonoBehaviour
  18. {
  19. // [Range(0, 600)]
  20. public float ViewSpeed = 600; // 旋转速度
  21. private float xValue;
  22. private float yValue;
  23. private Vector3 rotationValue = Vector3.zero;
  24. private Transform cameraTrC;
  25. private void Start()
  26. {
  27. if (!Camera.main)
  28. {
  29. TipTools.Error("[CameraLookAround] " + "Cant find Camera.");
  30. this.enabled = false;
  31. return;
  32. }
  33. this.cameraTrC = Camera.main.transform;
  34. }
  35. private void Update()
  36. {
  37. this.RotateViewTrigger();
  38. }
  39. private void RotateViewTrigger()
  40. {
  41. if (Input.GetMouseButton(0)) // 按住鼠标左键
  42. {
  43. this.xValue = Input.GetAxis("Mouse X");
  44. this.yValue = Input.GetAxis("Mouse Y");
  45. if (this.xValue != 0 || this.yValue != 0) // 并且鼠标移动
  46. {
  47. // transform.Rotate(0, xValue * speed * Time.deltaTime, 0, Space.World);
  48. // transform.Rotate(yValue * -speed * Time.deltaTime, 0, 0, Space.Self); // 左右
  49. this.RotateView(this.cameraTrC, this.xValue, this.yValue, this.ViewSpeed);
  50. }
  51. }
  52. return;
  53. }
  54. /// <summary>
  55. /// 视角滚动
  56. /// </summary>
  57. /// <param name="x"></param>
  58. /// <param name="y"></param>
  59. private void RotateView(Transform objectTrC, float x, float y, float speed)
  60. {
  61. this.rotationValue.x += y * Time.deltaTime * speed;
  62. this.rotationValue.y += x * Time.deltaTime * -speed;
  63. if (this.rotationValue.x > 90) // 矫正
  64. {
  65. this.rotationValue.x = 90;
  66. }
  67. else if (this.rotationValue.x < -90)
  68. {
  69. this.rotationValue.x = -90;
  70. }
  71. objectTrC.rotation = Quaternion.Euler(this.rotationValue);
  72. return;
  73. }
  74. }
  75. }