KeyboardBowController.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. public class KeyboardBowController : MonoBehaviour
  3. {
  4. [Header("W/S 上下、A/D 左右、Q/ 射击/ 、Y/U 胜利/失败")]
  5. public float rotateSpeed = 60f; // 每秒旋转角度
  6. public bool smooth = false; // 是否平滑旋转
  7. public float smoothSpeed = 10f;
  8. private Quaternion targetRotation;
  9. void Start()
  10. {
  11. if (CameraToLook.ins == null)
  12. {
  13. Debug.LogError("CameraToLook.ins 未找到!");
  14. enabled = false;
  15. return;
  16. }
  17. targetRotation = CameraToLook.ins.localRotation;
  18. }
  19. void Update()
  20. {
  21. HandleKeyboardInput();
  22. if (smooth)
  23. {
  24. CameraToLook.ins.localRotation =
  25. Quaternion.Slerp(CameraToLook.ins.localRotation, targetRotation, Time.deltaTime * smoothSpeed);
  26. }
  27. else
  28. {
  29. CameraToLook.ins.localRotation = targetRotation;
  30. }
  31. }
  32. /**
  33. * 如果是屏幕坐标
  34. * Ray ray = Camera.main.ScreenPointToRay(point);
  35. Vector3 rayEndPoint = ray.GetPoint(200);
  36. Quaternion quat = Quaternion.LookRotation(rayEndPoint - Camera.main.transform.position);
  37. // 挑战场景中其相机的父级有旋转,需要换算
  38. quat = Quaternion.AngleAxis(-180, Vector3.up) * quat;
  39. if (CameraToLook.ins != null) CameraToLook.ins.localRotation = quat;
  40. */
  41. void HandleKeyboardInput()
  42. {
  43. float delta = rotateSpeed * Time.deltaTime;
  44. // 上下(X轴旋转)
  45. if (Input.GetKey(KeyCode.W))
  46. targetRotation *= Quaternion.Euler(-delta, 0, 0);
  47. if (Input.GetKey(KeyCode.S))
  48. targetRotation *= Quaternion.Euler(delta, 0, 0);
  49. // 左右(Y轴旋转)
  50. if (Input.GetKey(KeyCode.A))
  51. targetRotation *= Quaternion.Euler(0, -delta, 0);
  52. if (Input.GetKey(KeyCode.D))
  53. targetRotation *= Quaternion.Euler(0, delta, 0);
  54. }
  55. }