SurroundCaptureDemo.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. //-----------------------------------------------------------------------------
  4. // Copyright 2012-2017 RenderHeads Ltd. All rights reserved.
  5. //-----------------------------------------------------------------------------
  6. namespace RenderHeads.Media.AVProMovieCapture.Demos
  7. {
  8. /// <summary>
  9. /// Spawns cube prefabs from a transform and removes them once they reach a maximum number
  10. /// </summary>
  11. public class SurroundCaptureDemo : MonoBehaviour
  12. {
  13. [SerializeField]
  14. private Transform _spawnPoint;
  15. [SerializeField]
  16. private GameObject _cubePrefab;
  17. [SerializeField]
  18. private bool _spawn = true;
  19. private const int MaxCubes = 48;
  20. private const float SpawnTime = 0.25f;
  21. // State
  22. private float _timer = SpawnTime;
  23. private List<GameObject> _cubes = new List<GameObject>(32);
  24. private void Update()
  25. {
  26. // Spawn cubes at a certain rate
  27. _timer -= Time.deltaTime;
  28. if (_timer <= 0f)
  29. {
  30. if (_spawn)
  31. {
  32. _timer = SpawnTime;
  33. SpawnCube();
  34. }
  35. // Remove cubes when there are too many
  36. if (_cubes.Count > MaxCubes || !_spawn)
  37. {
  38. RemoveCube();
  39. }
  40. }
  41. }
  42. private void SpawnCube()
  43. {
  44. Quaternion rotation = Quaternion.Euler(Random.Range(-180f, 180f), Random.Range(-180f, 180f), Random.Range(-180f, 180f));
  45. float scale = Random.Range(0.1f, 0.6f);
  46. GameObject go = (GameObject)GameObject.Instantiate(_cubePrefab, _spawnPoint.position, rotation);
  47. Transform t = go.GetComponent<Transform>();
  48. go.GetComponent<Rigidbody>().AddExplosionForce(10f, _spawnPoint.position, 5f, 0f, ForceMode.Impulse);
  49. //AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier = 0.0F, ForceMode mode = ForceMode.Force);
  50. t.localScale = new Vector3(scale * 2f, scale, scale * 2f);
  51. t.SetParent(_spawnPoint);
  52. _cubes.Add(go);
  53. }
  54. private void RemoveCube()
  55. {
  56. if (_cubes.Count > 0)
  57. {
  58. // Remove the oldest cube
  59. GameObject go = _cubes[0];
  60. // Disabling the collider makes it fall through the floor - which is a neat way to hide its removal
  61. go.GetComponent<Collider>().enabled = false;
  62. _cubes.RemoveAt(0);
  63. StartCoroutine("KillCube", go);
  64. }
  65. }
  66. private System.Collections.IEnumerator KillCube(GameObject go)
  67. {
  68. yield return new WaitForSeconds(1.5f);
  69. Destroy(go);
  70. }
  71. }
  72. }