AnswerOption.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using UnityEngine;
  2. using TMPro;
  3. using System;
  4. public class AnswerOption : MonoBehaviour
  5. {
  6. [SerializeField] private TextMeshPro answerText;
  7. private int answerValue;
  8. private MathQuizManager quizManager;
  9. private bool isCorrect;
  10. private Vector3 startPos, targetPos;
  11. private float showTime = 0.8f, disappearTime = 1f, floatHeight = 3f;
  12. private float showT = 0f, disappearT = 0f;
  13. private bool isShown = false, isDisappearing = false;
  14. public static event Action OnAnswerClicked;
  15. void Start()
  16. {
  17. if (!answerText) answerText = GetComponentInChildren<TextMeshPro>();
  18. startPos = transform.position;
  19. targetPos = startPos + Vector3.up * floatHeight;
  20. Destroy(gameObject, showTime + disappearTime + 15f);
  21. }
  22. public void Initialize(MathQuizManager mgr, int value, bool correct)
  23. {
  24. quizManager = mgr;
  25. answerValue = value;
  26. isCorrect = correct;
  27. if (answerText) answerText.text = value.ToString();
  28. Invoke(nameof(StartDisappear), 15f);
  29. }
  30. void Update()
  31. {
  32. if (isDisappearing)
  33. {
  34. disappearT += Time.deltaTime;
  35. float t = Mathf.Clamp01(disappearT / disappearTime);
  36. transform.position = Vector3.Lerp(transform.position, transform.position + Vector3.up * floatHeight, t);
  37. transform.localScale = Vector3.Lerp(Vector3.one, Vector3.zero, t);
  38. if (t >= 1f) Destroy(gameObject);
  39. }
  40. else if (!isShown)
  41. {
  42. showT += Time.deltaTime;
  43. float t = Mathf.Clamp01(showT / showTime);
  44. transform.position = Vector3.Lerp(startPos, targetPos, t);
  45. transform.localScale = Vector3.Lerp(Vector3.zero, Vector3.one, t);
  46. if (t >= 1f) isShown = true;
  47. }
  48. else
  49. {
  50. transform.position = Vector3.Lerp(transform.position, targetPos, 0.3f * Time.deltaTime);
  51. }
  52. }
  53. void StartDisappear() { isDisappearing = true; disappearT = 0f; }
  54. void OnMouseDown()
  55. {
  56. if (quizManager != null && isShown && !isDisappearing)
  57. {
  58. quizManager.CheckAnswer(this);
  59. StartDisappear();
  60. OnAnswerClicked?.Invoke();
  61. }
  62. }
  63. public int GetAnswerValue() => answerValue;
  64. }