π Full explanation & examples
When you register a Component with display.add(obj, 2), the engine stores the number 2 alongside that Component in the comm[] array. Every frame, the render loop checks if (component.scene == display.scene) before drawing anything. Components in scenes 1 and 2 are completely invisible and receive no move() or update() calls when display.scene is 0.
Changing display.scene = 1 takes effect on the very next frame β the menu Components stop rendering and the gameplay Components instantly become active, with zero allocation or garbage collection overhead. This is the recommended pattern for any game state transition β never call destroy() on UI elements that will be needed again, and never re-create objects on every state change; just assign them to their scene at startup and flip display.scene as needed.
// Build all scenes at startup
const menuBtn = new Component(160, 50, "#7fffb2", 320, 275, "rect");
display.add(menuBtn, 0); // scene 0 = menu
const player = new Component(40, 40, "cyan", 100, 100, "rect");
const gameUI = new Tctxt("18px","Arial","white",14,28,"left",false,"alphabetic","rgba(0,0,0,0.5)",8,4);
gameUI.setText("Score: 0");
display.add(player, 1); // scene 1 = gameplay
display.add(gameUI, 1);
const gameOverMsg = new Tctxt("40px","Arial","red",220,260,"center");
gameOverMsg.setText("GAME OVER");
display.add(gameOverMsg, 2); // scene 2 = game over
display.scene = 0; // start on menu
function update() {
if (display.scene === 0 && display.x && menuBtn.clicked()) {
display.scene = 1;
}
if (display.scene === 1) {
// all gameplay logic here
gameUI.fixed();
}
}
π‘ Scenes are just integers β you can have as many as you need. Use constants like const SCENE_MENU = 0, SCENE_GAME = 1, SCENE_GAMEOVER = 2 for readability.