ExamplePhysics.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Chronos.Example
  5. {
  6. // An example for Chronos with physics.
  7. // Will spawn a certain amount of boxes at random positions
  8. // in the air and attach the proper components to them for
  9. // Chronos support.
  10. public class ExamplePhysics : ExampleBaseBehaviour
  11. {
  12. // The delay between respawns
  13. public float delay = 5;
  14. // The amount of boxes to spawn
  15. public float amount = 10;
  16. // The list of spawned boxes
  17. private List<GameObject> spawned = new List<GameObject>();
  18. private void Start()
  19. {
  20. // Start spawning
  21. StartCoroutine(SpawnCoroutine());
  22. }
  23. private IEnumerator SpawnCoroutine()
  24. {
  25. // Loop forever
  26. while (true)
  27. {
  28. // Spawn the boxes
  29. Spawn();
  30. // Wait for the delay, taking in consideration
  31. // the time scales. Notice "time.WaitForSeconds"
  32. // instead of "new WaitForSeconds"
  33. yield return time.WaitForSeconds(delay);
  34. }
  35. }
  36. // Spawn the boxes
  37. private void Spawn()
  38. {
  39. // Clear the previously spawned boxes
  40. foreach (GameObject go in spawned)
  41. {
  42. Destroy(go);
  43. }
  44. spawned.Clear();
  45. for (int i = 0; i < amount; i++)
  46. {
  47. // Create a cube
  48. GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
  49. // Place it in the air at a random position
  50. go.transform.position = transform.position;
  51. go.transform.position += new Vector3()
  52. {
  53. x = Random.Range(-1f, +1f),
  54. y = 2 * i,
  55. z = Random.Range(-1f, +1f)
  56. };
  57. // Give it a rigidbody
  58. go.AddComponent<Rigidbody>();
  59. // Give it a timeline in that watches the same
  60. // global clock as this component
  61. Timeline timeline = go.AddComponent<Timeline>();
  62. timeline.mode = TimelineMode.Global;
  63. timeline.globalClockKey = time.globalClockKey;
  64. timeline.rewindable = time.rewindable;
  65. // Add the time-color script for easy visualisation
  66. go.AddComponent<ExampleTimeColor>();
  67. // Store the spawned object so we can destroy it on respawn
  68. spawned.Add(go);
  69. }
  70. }
  71. }
  72. }