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.

68 lines
2.2 KiB

  1. namespace VRTK.Examples
  2. {
  3. using UnityEngine;
  4. public class LightSaber : VRTK_InteractableObject
  5. {
  6. private bool beamActive = false;
  7. private Vector2 beamLimits = new Vector2(0f, 1.2f);
  8. private float currentBeamSize;
  9. private float beamExtendSpeed = 0;
  10. private GameObject blade;
  11. private Color activeColor;
  12. private Color targetColor;
  13. private Color[] bladePhaseColors;
  14. public override void StartUsing(VRTK_InteractUse currentUsingObject = null)
  15. {
  16. base.StartUsing(currentUsingObject);
  17. beamExtendSpeed = 5f;
  18. bladePhaseColors = new Color[2] { Color.blue, Color.cyan };
  19. activeColor = bladePhaseColors[0];
  20. targetColor = bladePhaseColors[1];
  21. }
  22. public override void StopUsing(VRTK_InteractUse previousUsingObject = null, bool resetUsingObjectState = true)
  23. {
  24. base.StopUsing(previousUsingObject, resetUsingObjectState);
  25. beamExtendSpeed = -5f;
  26. }
  27. protected void Start()
  28. {
  29. blade = transform.Find("Blade").gameObject;
  30. currentBeamSize = beamLimits.x;
  31. SetBeamSize();
  32. }
  33. protected override void Update()
  34. {
  35. base.Update();
  36. currentBeamSize = Mathf.Clamp(blade.transform.localScale.y + (beamExtendSpeed * Time.deltaTime), beamLimits.x, beamLimits.y);
  37. SetBeamSize();
  38. PulseBeam();
  39. }
  40. private void SetBeamSize()
  41. {
  42. blade.transform.localScale = new Vector3(1f, currentBeamSize, 1f);
  43. beamActive = (currentBeamSize >= beamLimits.y ? true : false);
  44. }
  45. private void PulseBeam()
  46. {
  47. if (beamActive)
  48. {
  49. Color bladeColor = Color.Lerp(activeColor, targetColor, Mathf.PingPong(Time.time, 1));
  50. blade.transform.Find("Beam").GetComponent<MeshRenderer>().material.color = bladeColor;
  51. if (bladeColor == targetColor)
  52. {
  53. var previouslyActiveColor = activeColor;
  54. activeColor = targetColor;
  55. targetColor = previouslyActiveColor;
  56. }
  57. }
  58. }
  59. }
  60. }