💠 Global Physics System (Gravity and Movement)

The engine includes a lightweight and efficient 2D global physics system designed to handle gravity, movement, collisions, and ground detection. This system runs automatically every frame, affecting all objects that require it.

⚙️ Basic Concepts

📦 Movement Properties

🌍 Gravity

Gravity is applied cumulatively on the Y axis. If an object has gravity = 800, its vertical velocity increases by 800 pixels/second every second (free fall).

// Example: manually applying gravity
if (obj.gravity) {
  obj.vy += obj.gravity * dt;
  obj.y  += obj.vy * dt;
}
🔹 Objects with static = true or trigger = true are not affected by gravity.
🔹 Gravity is only applied when the object is active (active = true).

🏃 Movement

Movement is calculated from velocity and delta time:

obj.x += obj.vx * dt;
obj.y += obj.vy * dt;

The collision system automatically corrects the object's position if a collision is detected, preventing overlaps or infinite falling.

🧱 Ground Detection

Each object maintains a boolean property onGround that indicates whether it is standing on a solid surface. This value updates automatically after collision resolution.

if (obj.onGround) {
  // The object is touching the ground
  obj.vy = 0;
}
🔸 Ideal for players, enemies, or moving platforms.
🔸 If onGround = true and gravity > 0, the engine prevents vertical speed from accumulating downward.

🎯 Practical Examples

1️⃣ Basic Horizontal Movement

// Script: move_left_right.js
let speed = 200;

function Update(obj, dt) {
  if (keys["ArrowLeft"])      obj.vx = -speed;
  else if (keys["ArrowRight"]) obj.vx = speed;
  else obj.vx = 0;
}

2️⃣ Jump with Ground Detection

// Script: jump_player.js
let jumpForce = 400;

function Update(obj, dt) {
  if (obj.onGround && keys["Space"]) {
    obj.vy = -jumpForce;
    obj.onGround = false;
  }
}

3️⃣ Projectile-Type Movement

// Script: projectile.js
function Start(obj) {
  obj.vx = 600;  // horizontal velocity
  obj.vy = -200; // slight upward angle
  obj.gravity = 900;
}

🔄 Execution Order

  1. Update object position and gravity.
  2. Run collision detection.
  3. Correct positions and update flags (onGround).
  4. Trigger collision and trigger events.
⚙️ This flow ensures that all objects react to gravity and collisions in a single per-frame cycle, keeping optimal performance even with dozens of objects.

💡 Recommendations

📌 Summary

- Gravity only affects active, non-static objects.
- Objects update their position using vx and vy every frame.
- The system prevents overlaps and maintains correct onGround state.
- Execution order ensures consistency between physics and collisions.
- Arcade-style behaviors (bounces, speed limits) are implemented through scripts.

⚠️ Current Limitations

🧩 Future updates may include: