👾 Example Script - Enemy Patrol Between Waypoints

This script creates an enemy that moves horizontally between two defined points (Waypoint_1 and Waypoint_2), reversing direction when reaching them. It is ideal for 2D platformers, action or adventure games.

💡 Tip: make sure you have two objects named Waypoint_1 and Waypoint_2 in the scene. The enemy must have collisions and Trigger detection enabled to work correctly.

📜 Full Code

// ======================================================
// 👾 Enemy.js — Patrols between two Waypoints
// ======================================================

let Waypoint_1;
let Waypoint_2;
let Speed = 90;
let Direction = 1; // 0: left, 1: right

function Start(obj) {
  // Executes once at start
  Waypoint_1 = getObjectByName("Waypoint_1");
  Waypoint_2 = getObjectByName("Waypoint_2");
}

function Update(obj, dt) {
  // Horizontal movement (frame-rate independent)
  if (Direction === 1) {
    obj.x += Speed * dt;
  } else {
    obj.x -= Speed * dt;
  }
}

function OnTriggerEnter(obj, other) {
  // Change direction when touching each waypoint
  if (other.name === "Waypoint_1") {
    Direction = 1;
    obj.flipX = 0; // Look right
  }

  if (other.name === "Waypoint_2") {
    Direction = 0;
    obj.flipX = 1; // Look left
  }

  // If colliding with player, reload the scene
  if (other.tag === "Player") {
    ReloadScene();
  }
}

function OnCollisionEnter(obj, other) {
  // Additional collision logic (optional)
}

📘 Quick Description

🧠 Suggestion: you can place the waypoints closer or farther to adjust the enemy path, or change the Speed variable to modify patrol velocity.
⚙️ Extension: to add animations to the enemy, add an AnimationController component and use:
if (Direction === 1) PlayAnimation(obj, "WalkRight");
else PlayAnimation(obj, "WalkLeft");