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.
Waypoint_1 and
Waypoint_2 in the scene.
The enemy must have collisions and Trigger detection enabled to work correctly.
// ======================================================
// 👾 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)
}
Speed (pixels per second).Trigger with the waypoints.obj.flipX).ReloadScene().Speed variable to modify patrol velocity.
AnimationController component and use:
if (Direction === 1) PlayAnimation(obj, "WalkRight");
else PlayAnimation(obj, "WalkLeft");