Camera漫游控制脚本

作者:追风剑情 发布于:2025-3-14 15:16 分类:Unity3d

  1. using UnityEngine;
  2. /// <summary>
  3. /// 镜头漫游控制
  4. /// </summary>
  5. public class CameraRoaming : MonoBehaviour
  6. {
  7. [Tooltip("移动速度")]
  8. public float moveSpeed = 1.0f;
  9. [Tooltip("旋转速度")]
  10. public float rotationSpeed = 40.0f;
  11. [Header("按键设置")]
  12. [Tooltip("向前移动按键")]
  13. public KeyCode forwardKey = KeyCode.W;
  14. [Tooltip("向后移动按键")]
  15. public KeyCode backKey = KeyCode.S;
  16. [Tooltip("向左移动按键")]
  17. public KeyCode leftKey = KeyCode.A;
  18. [Tooltip("向右移动按键")]
  19. public KeyCode rightKey = KeyCode.D;
  20. [Tooltip("向左旋转按键")]
  21. public KeyCode leftRotateKey = KeyCode.Q;
  22. [Tooltip("向右旋转按键")]
  23. public KeyCode rightRotateKey = KeyCode.E;
  24.  
  25. private Transform m_Transform;
  26.  
  27. private void Awake()
  28. {
  29. m_Transform = transform;
  30. }
  31.  
  32. private void Update()
  33. {
  34. ForwardMove();
  35. BackMove();
  36. LeftMove();
  37. RightMove();
  38. LeftRotate();
  39. RightRotate();
  40. }
  41.  
  42. // 向前移动
  43. private void ForwardMove()
  44. {
  45. if (Input.GetKey(forwardKey))
  46. {
  47. m_Transform.Translate(m_Transform.forward * moveSpeed * Time.deltaTime, Space.World);
  48. }
  49. }
  50.  
  51. // 向后移动
  52. private void BackMove()
  53. {
  54. if (Input.GetKey(backKey))
  55. {
  56. m_Transform.Translate(-m_Transform.forward * moveSpeed * Time.deltaTime, Space.World);
  57. }
  58. }
  59.  
  60. // 向左移动
  61. private void LeftMove()
  62. {
  63. if (Input.GetKey(leftKey))
  64. {
  65. m_Transform.Translate(-m_Transform.right * moveSpeed * Time.deltaTime, Space.World);
  66. }
  67. }
  68.  
  69. // 向右移动
  70. private void RightMove()
  71. {
  72. if (Input.GetKey(rightKey))
  73. {
  74. m_Transform.Translate(m_Transform.right * moveSpeed * Time.deltaTime, Space.World);
  75. }
  76. }
  77.  
  78. // 向左旋转镜头
  79. private void LeftRotate()
  80. {
  81. if (Input.GetKey(leftRotateKey))
  82. {
  83. m_Transform.Rotate(-Vector3.up * rotationSpeed * Time.deltaTime, Space.World);
  84. }
  85. }
  86.  
  87. // 向右旋转镜头
  88. private void RightRotate()
  89. {
  90. if (Input.GetKey(rightRotateKey))
  91. {
  92. m_Transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime, Space.World);
  93. }
  94. }
  95. }

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号