Skip to content

token.getDistanceTo()

Measure the distance from this token to another, in grid units.

Part of the Action API · Function reference

Available on token, target, and every entry of targets.

Signature

token.getDistanceTo(otherToken: string | Token): number

Synchronous.

Parameters

Parameter Type Description
otherToken string | Token The other token, as an object (target, an entry of targets, anything with an id) or as a token id string.

Returns

number — the straight-line distance in grid squares, as a decimal. Diagonally adjacent tokens are about 1.41 apart, not 1.

Returns Infinity when the other token cannot be found — a stale id, or a token on another map. Guard for that before comparing.

How it measures

Euclidean distance between the two tokens' grid positions: the hypotenuse, not a count of squares walked. It does not apply your system's diagonal movement rule, does not account for token size, and does not care about walls or elevation.

To convert to your table's units, multiply by the size of a square:

const feet = token.getDistanceTo(target) * 5;

To count squares the way many systems do — diagonals as one — do the maths yourself from the coordinates:

const squares = Math.max(
  Math.abs(token.x - target.x),
  Math.abs(token.y - target.y),
);

Examples

Enforce a range

if (!target) return 'No target.';
if (token.getDistanceTo(target) > 6) {
  return `${target.name} is out of range.`;
}
target.applyDamage(roll('1d8+2'), 'force');

Melee only

const distance = token.getDistanceTo(target);
if (distance > 1.5) return 'Too far to reach.';

Falloff with distance

for (const t of targets) {
  const d = token.getDistanceTo(t);
  const damage = d <= 2 ? roll('4d6') : roll('2d6');
  t.applyDamage(damage, 'thunder');
}

Sort targets by proximity

const nearest = targets
  .slice()
  .sort((a, b) => token.getDistanceTo(a) - token.getDistanceTo(b))[0];

Notes and gotchas

  • Grid units, not feet. Multiply by your square size.
  • Decimals, not squares. Compare against a decimal threshold, or round.
  • Infinity is the failure value, so a naive distance > 6 check treats an unresolvable token as out of range — usually what you want, but be deliberate.
  • Positions are from the client's current view of the map, which may lag a move made a moment ago by someone else.
  • Nothing about line of sight. A token on the far side of a wall is still close. Pair with getLineOfSightTo().

See also