# Event order in ct.js

These events are always executed in the following order:

  1. Core ct.js library runs;
  2. Modules get initialized;
  3. Custom scripts added at project settings are executed;
  4. room's oncreate event is called, which is emitted when a user starts a game or navigates to a new room;
  5. oncreate is applied for each copy;
  6. then the main game loop starts:
    1. onstep event is emitted for all the copies in the room;
    2. onstep event for current room is called;
    3. ondestroy is called for all the copies marked to be killed;
    4. all the copies are reordered then;
    5. ondraw is called for all the copies;
    6. ondraw is called for a room;
    7. input events are cleared. Waiting for a new game loop iteration.
  7. When a user moves to a new room, an onleave event is called for the latest room.

# Call order with mod's injections

At startup:

  1. Core ct.js library runs.
  2. load.js.
  3. Modules get initialized.
  4. Custom scripts added at project settings are executed;
  5. resload.js runs once all the assets have finished loading.
  6. start.js — called right before a game is started (no room is created yet).
  7. The first room gets created.
  8. Room's OnCreate is called.
  9. roomoncreate.js.
  10. switch.js is called.
  11. ct.camera is properly positioned.

At room transition:

  1. Previous room's OnLeave event is called.
  2. roomonleave.js.
  3. New room's OnCreate is called.
  4. Copies are created here, with all their events and injections.
  5. roomoncreate.js
  6. switch.js
  7. ct.camera is properly positioned.

At each frame:

  1. beforeframe.js is run in global context.
  2. beforestep.js with this being the current type.
  3. Copies' own OnStep is called.
  4. afterstep.js with this being the current type.
  5. beforeroomstep.js with this being a current room (can be different from ct.room)
  6. Room's own OnStep is called.
  7. afterroomstep.js with this being a current room (can be different from ct.room)
  8. Copies get destroyed with their OnDestroy event.
  9. Camera position is updated
  10. beforedraw.js with this being the current type.
  11. Copies' own OnDraw is called.
  12. afterdraw.js with this being the current type.
  13. beforeroomdraw.js with this being a current room (can be different from ct.room)
  14. Room's own OnDraw is called.
  15. afterroomdraw.js with this being a current room (can be different from ct.room)
  16. afterframe.js is called before moving on to the next frame.

At copy creation:

  1. onbeforecreate.js
  2. Copies' own OnCreate is called.
  3. oncreate.js

At copy deletion:

  1. ondestroy.js
  2. Copy's own OnDestroy event is called.