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.

111 lines
2.7 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using VRTK;
  5. using VRTK.SecondaryControllerGrabActions;
  6. public class BowGrab : VRTK_ControlDirectionGrabAction
  7. {
  8. [SerializeField]
  9. private Vector3 m_angleOffset;
  10. [SerializeField]
  11. private Transform m_notchPoint;
  12. [Header("Pull settings")]
  13. [SerializeField]
  14. private float m_maxPullDistance = 0.5f;
  15. [SerializeField]
  16. private string m_animationParam = "bowPull";
  17. [Header("Arrow Settings")]
  18. [SerializeField]
  19. private GameObject m_arrowPrefab;
  20. [SerializeField]
  21. private Transform m_arrowSpawn;
  22. [SerializeField]
  23. private float m_maxForce = 10f;
  24. private Animator m_animator;
  25. private Vector3 m_lastForward;
  26. private float m_lastForce;
  27. private void Start()
  28. {
  29. m_animator = GetComponent<Animator>();
  30. }
  31. public override void ProcessFixedUpdate()
  32. {
  33. if (initialised)
  34. {
  35. AimObject();
  36. PullBow();
  37. }
  38. }
  39. protected override void AimObject()
  40. {
  41. Vector3 direction = Vector3.Slerp((primaryGrabbingObject.transform.position - secondaryGrabbingObject.transform.position).normalized, primaryGrabbingObject.transform.forward, 0.5f);
  42. transform.rotation = Quaternion.LookRotation(direction, primaryGrabbingObject.transform.up) * Quaternion.Euler(m_angleOffset);
  43. m_lastForward = direction;
  44. }
  45. protected virtual void PullBow()
  46. {
  47. float animationValue = getBowForce();
  48. m_animator.SetFloat(m_animationParam, animationValue);
  49. m_lastForce = animationValue;
  50. }
  51. public override void ResetAction()
  52. {
  53. base.ResetAction();
  54. m_animator.SetFloat(m_animationParam, 0);
  55. if (m_lastForce > 0.1f)
  56. {
  57. GameObject arrow = Instantiate(m_arrowPrefab);
  58. arrow.transform.position = m_arrowSpawn.transform.position;
  59. arrow.transform.forward = m_lastForward;
  60. Rigidbody rb = arrow.GetComponent<Rigidbody>();
  61. rb.velocity = arrow.transform.forward * m_lastForce * m_maxForce;
  62. }
  63. m_lastForce = 0;
  64. m_lastForward = Vector3.zero;
  65. }
  66. private float getBowForce()
  67. {
  68. Vector3 directionSecondHand = secondaryGrabbingObject.transform.position - m_notchPoint.transform.position;
  69. Vector3 directionPrimaryHand = primaryGrabbingObject.transform.position - m_notchPoint.transform.position;
  70. float force = 0;
  71. if (Vector3.Dot(directionSecondHand, directionPrimaryHand) > 0)
  72. force = 0;
  73. else
  74. {
  75. force = directionSecondHand.magnitude / m_maxPullDistance;
  76. if (force > 1)
  77. force = 1;
  78. }
  79. return force;
  80. }
  81. }