Création d'un petit party-game anonyme de Build + Bagar sous Unity
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

FreeCam.cs 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using UnityEngine.InputSystem;
  3. public class FreeCam : MonoBehaviour
  4. {
  5. [Header("Controls")]
  6. public float moveSpeed = 10f;
  7. public bool ghost = true;
  8. [Header("Sensitivity")]
  9. public float XAxisSensitivity = 30f;
  10. public float YAxisSensitivity = 30f;
  11. [Space]
  12. [Range(0, 89)] public float MaxXAngle = 60f;
  13. // privates
  14. private Vector2 _inputMouse;
  15. private Vector2 _velocity;
  16. private CharacterController _controller;
  17. private float _rotationX;
  18. private void Start()
  19. {
  20. // TODO remove - doesn't belong here - test only
  21. Cursor.lockState = CursorLockMode.Locked;
  22. Cursor.visible = false;
  23. _inputMouse = Vector2.zero;
  24. _velocity = Vector2.zero;
  25. _controller = gameObject.GetComponent<CharacterController>();
  26. _rotationX = 0;
  27. }
  28. // Update is called once per frame
  29. // TODO test if checking (input values = 0) to avoid calculus reduces CPU usage
  30. private void Update()
  31. {
  32. float rotationHorizontal = _inputMouse.x * XAxisSensitivity * Time.deltaTime;
  33. float rotationVertical = _inputMouse.y * YAxisSensitivity * Time.deltaTime;
  34. // always rotate Y in global world space to avoid gimbal lock
  35. transform.Rotate(Vector3.up * rotationHorizontal, Space.World);
  36. float rotationY = transform.localEulerAngles.y;
  37. _rotationX += rotationVertical;
  38. _rotationX = Mathf.Clamp(_rotationX, -MaxXAngle, MaxXAngle);
  39. transform.localEulerAngles = new Vector3(-_rotationX, rotationY, 0);
  40. float translationX = _velocity.x * moveSpeed * Time.deltaTime;
  41. float translationZ = _velocity.y * moveSpeed * Time.deltaTime;
  42. Vector3 _move = new Vector3(translationX, 0f, translationZ);
  43. // ghost directly moves transform. non-ghost uses CharacterController collision detection
  44. if (ghost) {
  45. transform.Translate(_move);
  46. } else {
  47. _move = transform.TransformVector(_move);
  48. _controller.Move(_move);
  49. }
  50. }
  51. public void OnLook(InputValue value)
  52. {
  53. Vector2 valueAsVector2 = value.Get<Vector2>();
  54. _inputMouse.x = valueAsVector2.x;
  55. _inputMouse.y = valueAsVector2.y;
  56. }
  57. public void OnMovement(InputValue value)
  58. {
  59. Vector2 valueAsVector2 = value.Get<Vector2>();
  60. _velocity.x = valueAsVector2.x;
  61. _velocity.y = valueAsVector2.y;
  62. }
  63. }