This script creates a smart enemy that:
stopDistance).// ======================================================
// ποΈ Enemy_Follow.js β Chase with Raycast + Memory
// ======================================================
let Player_obj;
function Start(obj) {
obj.rayLength = 800;
obj.hitInfo = null;
obj.speed = obj.speed ?? 120;
// minimum distance where enemy stops
obj.stopDistance = obj.stopDistance ?? 80;
// last position where the player was seen
obj.lastSeenX = null;
obj.lastSeenY = null;
Player_obj = getObjectByName("Top-Down Player");
}
// ------------------------------------------------------
function Update(obj, dt) {
if (!Player_obj) return;
// ============================
// REAL OBJECT DIMENSIONS
// ============================
const realW = obj.w * obj.scaleX;
const realH = obj.h * obj.scaleY;
const originX = obj.x + realW / 2;
const originY = obj.y + realH / 2;
// ============================
// RAYCAST TOWARDS PLAYER (with debug)
// ============================
const hit = Raycast(
originX,
originY,
Player_obj.x,
Player_obj.y,
obj.rayLength,
true,
obj
);
obj.hitInfo = hit;
const seesPlayer = (!hit || hit.object === Player_obj);
// =====================================================
// IF ENEMY SEES PLAYER β MOVE TOWARDS HIM
// =====================================================
if (seesPlayer) {
// save last seen position
obj.lastSeenX = Player_obj.x;
obj.lastSeenY = Player_obj.y;
// distance to player
const dx = Player_obj.x - originX;
const dy = Player_obj.y - originY;
const dist = Math.hypot(dx, dy);
// stop when too close
if (dist > obj.stopDistance) {
moveTowards(obj, Player_obj.x, Player_obj.y, dt);
}
return;
}
// =====================================================
// IF PLAYER IS NOT SEEN β MOVE TO LAST KNOWN POSITION
// =====================================================
if (obj.lastSeenX !== null) {
moveTowards(obj, obj.lastSeenX, obj.lastSeenY, dt);
// check if enemy reached the point
const dx = obj.lastSeenX - originX;
const dy = obj.lastSeenY - originY;
const dist = Math.hypot(dx, dy);
if (dist < 8) {
// forget last known position
obj.lastSeenX = null;
obj.lastSeenY = null;
}
}
}
// ------------------------------------------------------
// Helper function β move toward target point
// ------------------------------------------------------
function moveTowards(obj, tx, ty, dt) {
const realW = obj.w * obj.scaleX;
const realH = obj.h * obj.scaleY;
const cx = obj.x + realW / 2;
const cy = obj.y + realH / 2;
const dx = tx - cx;
const dy = ty - cy;
const dist = Math.hypot(dx, dy);
if (dist < 1) return;
obj.x += (dx / dist) * obj.speed * dt;
obj.y += (dy / dist) * obj.speed * dt;
}
stopDistance controls how close the enemy approaches.stopDistance for ranged enemies or melee enemies.
PlayAnimation(obj, "Walk");
PlayAnimation(obj, "Idle");