Planting.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using Valve.VR.InteractionSystem;
  6. namespace Valve.VR.InteractionSystem.Sample
  7. {
  8. public class Planting : MonoBehaviour
  9. {
  10. public SteamVR_Action_Boolean plantAction;
  11. public Hand hand;
  12. public GameObject prefabToPlant;
  13. private void OnEnable()
  14. {
  15. if (hand == null)
  16. hand = this.GetComponent<Hand>();
  17. if (plantAction == null)
  18. {
  19. Debug.LogError("<b>[SteamVR Interaction]</b> No plant action assigned", this);
  20. return;
  21. }
  22. plantAction.AddOnChangeListener(OnPlantActionChange, hand.handType);
  23. }
  24. private void OnDisable()
  25. {
  26. if (plantAction != null)
  27. plantAction.RemoveOnChangeListener(OnPlantActionChange, hand.handType);
  28. }
  29. private void OnPlantActionChange(SteamVR_Action_Boolean actionIn, SteamVR_Input_Sources inputSource, bool newValue)
  30. {
  31. if (newValue)
  32. {
  33. Plant();
  34. }
  35. }
  36. public void Plant()
  37. {
  38. StartCoroutine(DoPlant());
  39. }
  40. private IEnumerator DoPlant()
  41. {
  42. Vector3 plantPosition;
  43. RaycastHit hitInfo;
  44. bool hit = Physics.Raycast(hand.transform.position, Vector3.down, out hitInfo);
  45. if (hit)
  46. {
  47. plantPosition = hitInfo.point + (Vector3.up * 0.05f);
  48. }
  49. else
  50. {
  51. plantPosition = hand.transform.position;
  52. plantPosition.y = Player.instance.transform.position.y;
  53. }
  54. GameObject planting = GameObject.Instantiate<GameObject>(prefabToPlant);
  55. planting.transform.position = plantPosition;
  56. planting.transform.rotation = Quaternion.Euler(0, Random.value * 360f, 0);
  57. planting.GetComponentInChildren<MeshRenderer>().material.SetColor("_TintColor", Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f));
  58. Rigidbody rigidbody = planting.GetComponent<Rigidbody>();
  59. if (rigidbody != null)
  60. rigidbody.isKinematic = true;
  61. Vector3 initialScale = Vector3.one * 0.01f;
  62. Vector3 targetScale = Vector3.one * (1 + (Random.value * 0.25f));
  63. float startTime = Time.time;
  64. float overTime = 0.5f;
  65. float endTime = startTime + overTime;
  66. while (Time.time < endTime)
  67. {
  68. planting.transform.localScale = Vector3.Slerp(initialScale, targetScale, (Time.time - startTime) / overTime);
  69. yield return null;
  70. }
  71. if (rigidbody != null)
  72. rigidbody.isKinematic = false;
  73. }
  74. }
  75. }