首页 > 代码库 > Unity3D 学习教程 14 C# 旋转镜头

Unity3D 学习教程 14 C# 旋转镜头

if(Input.GetKey(KeyCode.Q))
{
transform.Rotate(0,-50*Time.deltaTime,0,Space.Self);
}
if(Input.GetKey(KeyCode.E))
{
transform.Rotate(0,50*Time.deltaTime,0,Space.Self);
}

 

模仿WOW镜头操作

  1. using UnityEngine;
  2. using System.Collections;
  3. /// 
  4. /// 将此脚本附加到任意镜头上,可以使其拥有WOW镜头的控制方式
  5. /// 
  6. public class WowCamera : MonoBehaviour
  7. {
  8. /// 
  9. /// 镜头目标
  10. /// 
  11. public Transform Target;
  12. /// 
  13. /// 镜头离目标的距离
  14. /// 
  15. public float Distance = 30.0f;
  16. /// 
  17. /// 最大镜头距离
  18. /// 
  19. public float MaxDistance = 30.0f;
  20. /// 
  21. /// 鼠标滚轮拉近拉远速度系数
  22. /// 
  23. public float ScrollFactor = 10.0f;
  24. /// 
  25. /// 镜头旋转速度比率
  26. /// 
  27. public float RotateFactor = 10.0f;
  28. /// 
  29. /// 镜头水平环绕角度
  30. /// 
  31. public float HorizontalAngle = 45;
  32. /// 
  33. /// 镜头竖直环绕角度
  34. /// 
  35. public float VerticalAngle = 0;
  36. private Transform mCameraTransform;
  37. void Start()
  38. {
  39. mCameraTransform = transform;
  40. }
  41. void Update()
  42. {
  43. //滚轮向前:拉近距离;滚轮向后:拉远距离
  44. var scrollAmount = Input.GetAxis(GameSetting.MouseScrollWheel);
  45. Distance -= scrollAmount * ScrollFactor;
  46. //保证镜头距离合法
  47. if (Distance < 0)
  48. Distance = 0;
  49. else if (Distance > MaxDistance)
  50. Distance = MaxDistance;
  51. //按住鼠标左右键移动,镜头随之旋转
  52. var isMouseLeftButtonDown = Input.GetMouseButton(0);
  53. var isMouseRightButtonDown = Input.GetMouseButton(1);
  54. if (isMouseLeftButtonDown || isMouseRightButtonDown)
  55. {
  56. Screen.lockCursor = true;
  57. var axisX = Input.GetAxis(GameSetting.MouseX);
  58. var axisY = Input.GetAxis(GameSetting.MouseY);
  59. HorizontalAngle += axisX * RotateFactor;
  60. VerticalAngle += axisY * RotateFactor;
  61. if (isMouseRightButtonDown)
  62. {
  63. //如果是鼠标右键移动,则旋转人物在水平面上与镜头方向一致
  64. Target.rotation = Quaternion.Euler(0, HorizontalAngle, 0);
  65. }
  66. }
  67. else
  68. {
  69. Screen.lockCursor = false;
  70. }
  71. //按镜头距离调整位置和方向
  72. var rotation = Quaternion.Euler(-VerticalAngle, HorizontalAngle, 0);
  73. var offset = rotation * Vector3.back * Distance;
  74. mCameraTransform.position = Target.position + offset;
  75. mCameraTransform.rotation = rotation;
  76. }
  77. }

 

Unity3D 学习教程 14 C# 旋转镜头