This function returns the distance between two agents, using a specific distance function. You can pass the current agent's state
as one of the agents. The different distance functions are:
Euclidean (default)
function behavior(state, context) {const { neighborA, neighborB } = context.neighbors();// Find the closest of 2 neighbors to youconst distanceToA = hash_stdlib.distanceBetween(state, neighborA);const distanceToB = hash_stdlib.distanceBetween(state, neighborB);const closest = distanceToB > distanceToA ? "A" : "B";state.set("closest", closest);// Check if neighbors are closer to each other than to youconst neighborDistance = hash_stdlib.distanceBetween(neighborA, neighborB);const selfDistance = closest === "A" ? distanceToA : distanceToB;state.set("closer_to_neighbors", selfDistance < neighborDistance);}
This function returns the unit vector of the vec
array. You can use it to normalize an agent's direction vector after it's modified.
function behavior(state, context) {const dir = state.get("direction");// Modify the direction by adding a vector [1, 2, 0]dir[0] += 1;dir[1] += 2;// Turn it back into a unit vectorstate.set("direction", hash_stdlib.normalizeVector(dir));}
This function returns a random integer position within the bounds of the topology
. The Topology should be user-defined in globals.json (see Topology). By defaultz_plane
is false
and the returned position is in a 2D plane. Pass true to return a position in 3D space.
function behavior(state, context) {// Move to a random positionconst topology = context.globals().topology;const new_pos = hash_stdlib.randomPosition(topology);state.set("position", new_pos);}