CockMoveComp.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using UnityEngine;
  3. namespace Comp
  4. {
  5. public class CockMoveComp : MonoBehaviour
  6. {
  7. // 刚体
  8. private Rigidbody _rigidbody;
  9. // 水平运动相关
  10. private bool _isMoving; // 是否进行水平运动
  11. private float _movingTime; // 水平运动时间
  12. private const float MovingSpeed = 0.5f; // 移动速度
  13. private const float MovingTime = 0.4f; // 移动时间
  14. // 跳跃相关
  15. private const float HighJumpSpeed = 2.4f; // 高跳速度
  16. private const float LowJumpSpeed = 2f; // 低跳速度
  17. private Vector3 CreateMovingVector(float speed)
  18. {
  19. var forward = transform.forward;
  20. return new Vector3(speed * forward.x, 0, 0);
  21. }
  22. private Vector3 CreateJumpingVector(float y)
  23. {
  24. return Vector3.up * y;
  25. }
  26. public void Move()
  27. {
  28. _isMoving = true;
  29. _movingTime = MovingTime;
  30. }
  31. public void MoveAndNeverStop()
  32. {
  33. _isMoving = true;
  34. _movingTime = float.MaxValue;
  35. }
  36. public void Stop()
  37. {
  38. _isMoving = false;
  39. _movingTime = 0;
  40. }
  41. public void Jump(bool highJump)
  42. {
  43. var jumpSpeed = highJump ? HighJumpSpeed : LowJumpSpeed;
  44. var jumpingVector = CreateJumpingVector(jumpSpeed);
  45. _rigidbody.AddForce(jumpingVector, ForceMode.Impulse); // 添加力
  46. }
  47. private void Start()
  48. {
  49. _rigidbody = GetComponent<Rigidbody>();
  50. }
  51. private void FixedUpdate()
  52. {
  53. if (!_isMoving) return;
  54. var movingVector = CreateMovingVector(MovingSpeed);
  55. transform.position += movingVector * Time.deltaTime;
  56. _movingTime -= Time.deltaTime;
  57. if (_movingTime <= 0)
  58. _isMoving = false;
  59. }
  60. }
  61. }