The distance calculation is good so long the layer is centered and in front of the camera. Otherwise the distance increases and the object becomes out of focus,
For a more advance script check out :
https://www.motionscript.com/design-guide/auto-focus.html
target = thisComp.layer("target");
v1 = target.toWorld(target.anchorPoint) - toWorld([0,0,0]);
v2 = toWorldVec([0,0,1]);
dot(v1,v2)