A force-directed graph with d3-force
Updated
d3-force, imported from a CDN, lays out six linked balls: the simulation is ticked once a frame and its positions move the balls and the lines between them.
Watch the graph settle, then press Space to scatter it. Drag to orbit the camera, scroll to zoom.
A force-directed graph with d3-force
#pragma import([forceSimulation, forceManyBody, forceLink, forceCenter]="https://cdn.jsdelivr.net/npm/d3-force@3.0.1/+esm")#pragma lifecycle(startup, update)
const SCALE = 0.02; // simulation units to metresconst LINKS = [[0, 1], [0, 2], [0, 3], [1, 4], [2, 5], [3, 5]];
let balls = [];let nodes = [];let lines = null;let simulation = null;
function startup() { balls = self.parent.children.filter((child) => isEntity(child) && child !== self); nodes = balls.map(() => ({})); simulation = forceSimulation(nodes) .force('charge', forceManyBody().strength(-60)) .force('link', forceLink(LINKS.map(([source, target]) => ({ source, target }))).distance(40)) .force('center', forceCenter()) .stop(); // no timer: update ticks it once a frame
const ends = LINKS.flatMap(() => [new THREE.Vector3(), new THREE.Vector3()]); lines = new THREE.LineSegments( new THREE.BufferGeometry().setFromPoints(ends), new THREE.LineBasicMaterial({ color: '#f8fafc' }), ); self.parent.add(lines);}
function update() { if (Input.keyboard.isKeyReleased(Key.Space)) { nodes.forEach((node) => { node.x = Random.range(-80, 80); node.y = Random.range(-80, 80); }); simulation.alpha(1); // reheat }
simulation.tick(); nodes.forEach((node, i) => balls[i].setPosition(node.x * SCALE, node.y * SCALE, 0));
const ends = lines.geometry.attributes.position; LINKS.forEach(([a, b], i) => { ends.setXYZ(i * 2, nodes[a].x * SCALE, nodes[a].y * SCALE, 0); ends.setXYZ(i * 2 + 1, nodes[b].x * SCALE, nodes[b].y * SCALE, 0); }); ends.needsUpdate = true;}How it works
Section titled “How it works”The script is explained step by step in A force-directed graph with d3-force.
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.
ForceGraph.xrproj