Movement & Pathfinding
Important Building Blocks & Primitives
SimpleCharacterController
RigidBody
ChunkLattice
Basic Waypoint Movement Example
// ... other code
let targetWaypointIndex = 0;
const WAYPOINT_COORDINATES = [
{ x: -5, y: 1, z: -7 },
{ x: 15, y: 1, z: 10 },
{ x: 17, y: 1, z: -12 },
];
const cow = new Entity({
controller: new SimpleEntityController(),
modelUri: 'models/npcs/cow.gltf',
modelScale: 0.7,
modelLoopedAnimations: [ 'walk' ],
modelAnimationsPlaybackRate: 1.6, // roughly match the animation speed to the move speed we'll use
rigidBodyOptions: {
enabledRotations: { x: false, y: true, z: false }, // prevent flipping over when moving
},
});
// We want to face towards the target each tick, since our relative position
// to the target may change as we move from a previous waypoint to the next.
cow.on(EntityEvent.TICK, () => {
if (targetWaypointIndex >= WAYPOINT_COORDINATES.length) {
return; // reached final waypoint, no need to rotate
}
// continually face towards target as we move
const controller = cow.controller as SimpleEntityController;
const targetWaypoint = WAYPOINT_COORDINATES[targetWaypointIndex];
controller.face(targetWaypoint, 5);
});
cow.spawn(world, { x: 0, y: 3, z: 0 });
// Pathfind to the next waypoint as we reach each waypoint
const pathfind = () => {
if (targetWaypointIndex >= WAYPOINT_COORDINATES.length) {
cow.stopModelAnimations(['walk']);
cow.startModelLoopedAnimations(['idle']);
return; // reached final waypoint, no need to pathfind
}
const controller = cow.controller as SimpleEntityController;
const targetWaypoint = WAYPOINT_COORDINATES[targetWaypointIndex];
// Makes the controlled entity, the cow, start moving towards the waypoint
// It will automatically handle it's own internal tick for movement.
controller.move(targetWaypoint, 3, {
moveCompleteCallback: () => {
// pathfind to next waypoint
targetWaypointIndex++;
pathfind();
},
moveIgnoreAxes: { x: false, y: true, z: false }, // ignore our y position when considering if movement is complete
});
};
pathfind();
Complex A* Pathfinding
Last updated
