A guard that spots and chases the player
Updated
A guard patrols a loop with Steering Follow Path; when the camera comes within 15 m, the script hands over to Steering Pursue and speeds it up, and an Enable On Signal lights its alarm.
Scroll in to bring the camera closer than 15 m: once the guard faces you, it runs at you. Scroll out to let it return to its patrol. Drag to orbit the camera.
A guard that spots and chases the player
#pragma lifecycle(startup, update)
const SIGHT = 15; // metresconst ALERT_SPEED = 6; // metres per secondconst PATROL_SPEED = 2;
let pursue;let patrol;let character;let chasing = false;const me = new THREE.Vector3();const player = new THREE.Vector3();
function startup() { // The guard: Character Controller (controls: false), Steering Agent with // viewDistance 15 and viewAngle 120, a Steering Follow Path (repeat: 'repeat') // and a Steering Pursue with weight 0. character = self.parent.getComponent(CharacterControllerComponent); patrol = self.parent.getComponent(SteeringFollowPathComponent); pursue = self.parent.getComponent(SteeringPursueComponent); if (CameraDirector.main) pursue.setProps({ target: CameraDirector.main });}
function update() { if (!CameraDirector.main) return; self.parent.getWorldPosition(me); CameraDirector.main.getWorldPosition(player); const near = me.distanceTo(player) < SIGHT; if (near === chasing) return;
chasing = near; pursue.setProps({ weight: chasing ? 2 : 0 }); patrol.setProps({ weight: chasing ? 0 : 1 }); character.setProps({ speed: chasing ? ALERT_SPEED : PATROL_SPEED }); emit(chasing ? 'guard/alert' : 'guard/calm');}How it works
Section titled “How it works”The script is explained step by step in A guard that spots and chases the player.
Open it in XR Creator
Section titled “Open it in XR Creator”Download the project file below, then import it in XR Hub with Projects › New › Import, as described in Projects and templates. It opens in XR Creator with the same scene you see running above, each script already attached to its Behavior entity. From there you can edit the scripts, adjust components and their props, preview your changes, and deploy the result as a world of your own.
GuardChase.xrproj