A wandering villager
Updated
A villager picks a random reachable point near home with randomPoint, walks there with its Character Controller, rests two to five seconds on arrive, and sets off again.
Watch the villager wander around the walls, resting between walks. Drag to orbit the camera, scroll to zoom.
A wandering villager
#pragma lifecycle(startup, update)
const HOME_RANGE = 12; // metresconst home = new THREE.Vector3();let agent;let character;let resting = 0;
function startup() { // The villager has a NavMesh Agent, a Character Controller (controls: false) // and a Signal Emitter with the signal 'villager'. agent = self.parent.getComponent(NavMeshAgentComponent); character = self.parent.getComponent(CharacterControllerComponent); self.parent.getWorldPosition(home);
on('villager', (event) => { if (event.eventType === EventType.CharacterController.Arrive) resting = 2 + Math.random() * 3; });}
function update(dt) { if (character.destination || resting > 0) { resting -= dt; return; } const spot = agent.randomPoint(home, HOME_RANGE); if (spot) character.moveTo(spot);}How it works
Section titled “How it works”The script is explained step by step in A wandering villager.
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.
WanderingVillager.xrproj