Free Function Friday Ep.33 – locateMidPoint

May 06th 2016 08:00:31am

The Free Function Friday series has been going strong for thirty two solid weeks. I’d like to thank all of you for participating and sharing in this series, and with After Effects scripting in general.

locateMidPoint is a handy function for when you need to place a null, layer, object, etc… at the mid point between two or more layer locations. Say you have a layer positioned at an X value of 0, and a Y value of 0. You then have another layer at position of X value 10, and Y value of 10.

The resulting mid point would be an X value of 5, and a Y value of 5. This is a super simple explanation of what can get progressively more complicated. Imagine having more than six or so layers to do the math on, and the values were more fractional like [249.2485616, 751.9417431].

Let’s let the function do the math for us, shall we. Now this setup will only return the mid point value as a 2D or 3D vector array value, so you can easily use it to set the value of your mid point layer. If you wanted this layer to always stay at the mid point even if the source layers are animated, then you would want more of an expression code to do this. Scripts can apply expressions, but I will not be going over that here. You can use this as an exercise to practice your scripting.

For the expression code version you can visit the Expression Shorts – Auto Center Layer tutorial.

Source Code:

var layerCollection = app.project.activeItem.selectedLayers;
var layerCollectionLen = layerCollection.length;
var vecs = new Array();
for(var v=0; v < layerCollectionLen; v++){
	vecs.push(layerCollection[v].transform.position.value);
}

var myMidPoint = locateMidPoint(vecs, true);

var nullLocator = app.project.activeItem.layer(1);
nullLocator.transform.position.setValue(myMidPoint);

function locateMidPoint(aryOfVectors, dimension){
	if(aryOfVectors instanceof Array){
		var midPoint = addVecs(aryOfVectors);
		if(dimension == true){
			return [midPoint[0], midPoint[1]];
		}else{
			return [midPoint[0], midPoint[1], midPoint[2]];
		}
		function addVecs(vecs){ //[0,0] [0,0,0]
			var x = 0;
			var y = 0;
			var z = 0;
			var vecsLen = vecs.length;
			if(vecs[0].length == 2){//2D
				for(var v=0; v < vecsLen; v++){
					x += Number(vecs[v][0]);
					y += Number(vecs[v][1]);
				}
			}else{//3D
				for(var v=0; v < vecsLen; v++){
					x += Number(vecs[v][0]);
					y += Number(vecs[v][1]);
					z += Number(vecs[v][2]);
				}
			}
			if(z != 0){
				z = z/vecsLen;
			}
			return [x/vecsLen, y/vecsLen, z];
		}
	}
}
Checkout more:
Free Function Friday Ep.40 – getLayFXMatchNames
Free Function Friday Ep.18 – getAELanguage
Free Function Friday Ep.19 – getThirdPartyFX
Houdini Mardini Mud
Houdini Velocity Forces 2: Advanced