The answer returned is within 6% of the exact value and avoids the square and square root functions.

(Note: I see an old topic which says that you should be able to call distanceTo on other objects, but that didn’t seem to be working for me. I will re-investigate.)

Pretty cool! You should be able to get to our distance function if you have a Vector object, then you can do pos1.distance(pos2). If you have a unit or other visible object which has a pos, then you can do unit1.distanceTo(pos2). Note that the first is distance and the second is distanceTo, unfortunately.

If you just have two plain {x, y} objects, you can make one into a Vector to get access to distance like this: Vector(pos1.x, pos1.y).distance(pos2).

Also note that if you are just comparing distances and don’t care about the absolute value, you can always use pos1.distanceSquared(pos2) which also avoids the square root (the square root is the slow part).

Basically, everything you can do outside of player code will run a lot faster, because player code gets transpiled and error-checked and instrumented and all this stuff, whereas game engine code (even though it does the same things) just runs. CodeCombat’s implementation of Vector distance, for example, is pretty straightforward CoffeeScript:

distance: (other, useZ) ->
dx = @x - other.x
dy = @y - other.y
sum = dx * dx + dy * dy
if useZ
dz = @z - other.z
sum += dz * dz
Math.sqrt sum
distanceSquared: (other, useZ) ->
dx = @x - other.x
dy = @y - other.y
sum = dx * dx + dy * dy
if useZ
dz = @z - other.z
sum += dz * dz
sum

Hmm, I think probably you are finding the shell in the moment after it exploded but before it ceased to exist (while the explosion was ongoing). Maybe ignore shells without a targetPos? If shell.targetPos is defined, it’s already a Vector.