ObjectEmitter.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. using System;
  10. using System.Collections.Generic;
  11. using UnityEngine;
  12. namespace NRKernal.NRExamples
  13. {
  14. public class ObjectEmitter : MonoBehaviour
  15. {
  16. [SerializeField]
  17. Rigidbody obj;
  18. [SerializeField]
  19. int maxObjectNum = 100;
  20. [SerializeField]
  21. float minHeight;
  22. List<Rigidbody> activeObjects = new List<Rigidbody>();
  23. List<Rigidbody> reserveObjects = new List<Rigidbody>();
  24. void Update()
  25. {
  26. for (int i = activeObjects.Count - 1; i >= 0; i--)
  27. {
  28. if (activeObjects[i].transform.position.y < minHeight)
  29. {
  30. activeObjects[i].gameObject.SetActive(false);
  31. reserveObjects.Add(activeObjects[i]);
  32. activeObjects.RemoveAt(i);
  33. }
  34. }
  35. if (NRInput.GetButtonDown(ControllerButton.TRIGGER))
  36. {
  37. InstantiateObject();
  38. }
  39. }
  40. void InstantiateObject()
  41. {
  42. Rigidbody rigidbody;
  43. if (activeObjects.Count >= maxObjectNum)
  44. {
  45. rigidbody = activeObjects[0];
  46. activeObjects.RemoveAt(0);
  47. activeObjects.Add(rigidbody);
  48. }
  49. else if (reserveObjects.Count != 0)
  50. {
  51. rigidbody = reserveObjects[0];
  52. rigidbody.gameObject.SetActive(true);
  53. reserveObjects.RemoveAt(0);
  54. activeObjects.Add(rigidbody);
  55. }
  56. else
  57. {
  58. rigidbody = Instantiate(obj, transform);
  59. activeObjects.Add(rigidbody);
  60. }
  61. rigidbody.transform.position = NRFrame.HeadPose.position + NRFrame.HeadPose.forward * 0.3f;
  62. rigidbody.transform.rotation = NRFrame.HeadPose.rotation;
  63. rigidbody.velocity = NRFrame.HeadPose.forward * 2f;
  64. }
  65. }
  66. }