Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
3.0 KiB

  1. namespace VRTK.Examples.Archery
  2. {
  3. using UnityEngine;
  4. public class Arrow : MonoBehaviour
  5. {
  6. public float maxArrowLife = 10f;
  7. public float maxCollidedLife = 1f;
  8. [HideInInspector]
  9. public bool inFlight = false;
  10. private bool collided = false;
  11. private Rigidbody rigidBody;
  12. private GameObject arrowHolder;
  13. private Vector3 originalPosition;
  14. private Quaternion originalRotation;
  15. private Vector3 originalScale;
  16. private AudioSource source;
  17. public void SetArrowHolder(GameObject holder)
  18. {
  19. arrowHolder = holder;
  20. arrowHolder.SetActive(false);
  21. }
  22. public void OnNock()
  23. {
  24. collided = false;
  25. inFlight = false;
  26. }
  27. public void Fired()
  28. {
  29. if (source != null)
  30. {
  31. source.Play();
  32. }
  33. DestroyArrow(maxArrowLife);
  34. }
  35. public void ResetArrow()
  36. {
  37. DestroyArrow(maxCollidedLife);
  38. collided = true;
  39. inFlight = false;
  40. RecreateNotch();
  41. ResetTransform();
  42. }
  43. private void Start()
  44. {
  45. rigidBody = GetComponent<Rigidbody>();
  46. SetOrigns();
  47. source = GetComponent<AudioSource>();
  48. }
  49. private void SetOrigns()
  50. {
  51. originalPosition = transform.localPosition;
  52. originalRotation = transform.localRotation;
  53. originalScale = transform.localScale;
  54. }
  55. private void FixedUpdate()
  56. {
  57. if (!collided)
  58. {
  59. transform.LookAt(transform.position + rigidBody.velocity);
  60. }
  61. }
  62. private void OnCollisionEnter(Collision collision)
  63. {
  64. if (inFlight && isActiveAndEnabled && gameObject.activeInHierarchy)
  65. {
  66. ResetArrow();
  67. }
  68. }
  69. private void RecreateNotch()
  70. {
  71. //swap the arrow holder to be the parent again
  72. arrowHolder.transform.SetParent(null);
  73. arrowHolder.SetActive(true);
  74. //make the arrow a child of the holder again
  75. transform.SetParent(arrowHolder.transform);
  76. //reset the state of the rigidbodies and colliders
  77. GetComponent<Rigidbody>().isKinematic = true;
  78. GetComponent<Collider>().enabled = false;
  79. arrowHolder.GetComponent<Rigidbody>().isKinematic = false;
  80. }
  81. private void ResetTransform()
  82. {
  83. arrowHolder.transform.position = transform.position;
  84. arrowHolder.transform.rotation = transform.rotation;
  85. transform.localPosition = originalPosition;
  86. transform.localRotation = originalRotation;
  87. transform.localScale = originalScale;
  88. }
  89. private void DestroyArrow(float time)
  90. {
  91. Destroy(arrowHolder, time);
  92. Destroy(gameObject, time);
  93. }
  94. }
  95. }