πŸ“œ Script System

What is it?

The engine’s script system allows extending the behavior of objects through JavaScript code. Each object can have a single script assigned, defining the functions that the engine automatically executes at different points in the lifecycle.

πŸ“– Script lifecycle

🧩 Special parameters

obj

Reference to the scene object the script is attached to. Through obj you can access and modify its main properties:

function Start(obj) {
  obj.hp = 100;        // object health
  obj.x = 200;         // X position
  obj.y = 300;         // Y position
  obj.color = "#f00";  // color if it's a simple object
}

Common obj properties:

dt (Delta Time)

The time in seconds elapsed since the last frame. It ensures movements and animations remain FPS-independent.

function Update(obj, dt) {
  // Move 100 pixels per second to the right
  obj.x += 100 * dt;
}

πŸ‘‰ Whether the game runs at 30 FPS or 120 FPS, the movement remains the same because it depends on time, not frames.

βœ… Full example

// Script PlayerController.js

function Start(obj) {
  obj.hp = 100;
  console.log(obj.name + " ready with " + obj.hp + " HP");
}

function Update(obj, dt) {
  // Horizontal movement
  if (isKeyPressed("ArrowRight")) obj.x += 200 * dt;
  if (isKeyPressed("ArrowLeft"))  obj.x -= 200 * dt;

  // Simulate damage
  if (isKeyPressed("d")) {
    obj.hp -= 1;
    console.log("HP: " + obj.hp);
  }
}

function OnDestroy(obj) {
  console.log(obj.name + " removed");
}

πŸ“Œ Communication between scripts

Even though each object can only have one script, objects can still communicate with each other:

πŸ“Œ Notes

- Each object can have only one script assigned.
- Scripts load at scene start, but only run on active objects.
- Use obj to access the object and dt for time-based logic.
- Keep scripts clean and organized, one per responsibility (e.g., PlayerController, EnemyAI, GameManager).