PianoColliderKey.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using DG.Tweening;
  5. [RequireComponent(typeof(AudioSource))]
  6. [RequireComponent(typeof(BoxCollider))]
  7. public class PianoColliderKey : MonoBehaviour
  8. {
  9. public Transform visualMove;
  10. public AudioClip pianoKeyAudio;
  11. private AudioSource audioSource;
  12. private BoxCollider boxCollider;
  13. private Vector3 initLocalPosition = Vector3.zero;
  14. private Tween moveTween;
  15. private bool isPianoKeyDown = false;
  16. private float duration = 0.1f;
  17. private int enterCount = 0;
  18. private void OnTriggerEnter(Collider other)
  19. {
  20. if (!CheckIsFrontPress(other))
  21. {
  22. Debug.Log("NotFront");
  23. return;
  24. }
  25. if (enterCount == 0)
  26. {
  27. PianoKeyDown();
  28. }
  29. else
  30. {
  31. Debug.Log("EnterCount != 0 " + other.gameObject.name);
  32. }
  33. enterCount++;
  34. }
  35. private void OnTriggerExit(Collider other)
  36. {
  37. if (enterCount == 0)
  38. {
  39. return;
  40. }
  41. enterCount--;
  42. if (enterCount == 0)
  43. {
  44. PianoKeyUp();
  45. }
  46. }
  47. private void Awake()
  48. {
  49. if (visualMove != null)
  50. {
  51. initLocalPosition = visualMove.transform.localPosition;
  52. }
  53. boxCollider = this.GetComponent<BoxCollider>();
  54. audioSource = this.GetComponent<AudioSource>();
  55. }
  56. private void PianoKeyDown()
  57. {
  58. if (isPianoKeyDown)
  59. {
  60. return;
  61. }
  62. isPianoKeyDown = true;
  63. if (visualMove != null)
  64. {
  65. audioSource.PlayOneShot(pianoKeyAudio);
  66. if (moveTween != null && moveTween.IsPlaying())
  67. {
  68. moveTween.Kill();
  69. }
  70. moveTween = visualMove.transform.DOLocalMoveZ(initLocalPosition.z + (boxCollider.size.z / 2f * 0.35f), duration);
  71. }
  72. }
  73. private void PianoKeyUp()
  74. {
  75. if (!isPianoKeyDown)
  76. {
  77. return;
  78. }
  79. isPianoKeyDown = false;
  80. if (visualMove != null)
  81. {
  82. if (moveTween != null && moveTween.IsPlaying())
  83. {
  84. moveTween.Kill();
  85. }
  86. moveTween = visualMove.transform.DOLocalMoveZ(initLocalPosition.z, duration);
  87. }
  88. }
  89. private bool CheckIsFrontPress(Collider collider)
  90. {
  91. Vector3 keyUp = -Vector3.forward;
  92. Vector3 pokeVector = transform.InverseTransformPoint(collider.transform.position) - boxCollider.center;
  93. float distance = Vector3.Dot(pokeVector, keyUp.normalized);
  94. float colliderHalfLength = boxCollider.size.z / 2f;
  95. return distance >= (colliderHalfLength * 0.8f);
  96. }
  97. }