ease(( (transform.position +thisComp.layer("PARENT").transform.position -thisComp.layer("CAMERA").transform.position) /300), 0, 100)
This expression takes the current layer Z depth, adds in the parent’s Z depth (useful only if the layer is parented to another, delete this part if it’s not), subtracts the position of the camera, and divides the result by the distance you want it to start fading to 0. Ease then takes the following two numbers and blends between them based on the previous calculations (100 when the camera is at the specified distance value or further away, 0 once the camera reaches the same depth as the layer).
This is especially useful when setting up a composition to fly through multiple images of clouds; it’s obvious as the camera passes through the layers they are just flat images, not volumetric masses of vapour. What you want is to fade out the layer as the camera gets closer, making it appear to fly through the cloud, instead of suddenly disappearing when it passes through the flat image. This script fixes the issue beatifully, creating a sense of volume and depth to an otherwise flat effect.
If there are a lot of layers using this script, it may be easiest to link the distance value to a master slider, making global scene changes very easy.
startFade = 500; // Start fade 500 pixels from camera. endFade = 1500; // End fade 1500 pixels from camera. C = thisComp.activeCamera.toWorld([0,0,0]); P = toWorld(anchorPoint); d = length(C,P); linear(d,startFade,endFade,0,100)
This variation is taken more directly from the Adobe help documentation. It’s usefulness is a bit different, giving more accurate distances (3D instead of 1D), but less automatic setup of the effect (without easing, it may require more manual input to finesse the animation). The versatility pays off, however, once you start applying it to more than just opacity effects.