Recursive expression with sampleimage
- October 25, 2023
- 3 replies
- 1007 views
Hi
I have a project were I try to put one layer (dot) on another layer (circle) with an expression. My plan was to
1. Find a random position for the dot layer.
2. Check if that position is on top of the circle layer, using sampleImage.
3. If it isn't, run a recursive call of the function.
It doesn't seem to work. I'm almost sure the expression is correct, but AE keep crashing. As if I had made an endless loop recursive call. Of course I could be missing something.
The expression looks like this:
function findPointOnLayer(targetLayer, functionSeed)
{
seedRandom(functionSeed, true);
var rndX = Math.random();
var rndY = Math.random();
var posX = thisComp.width * rndX;
var posY = thisComp.height * rndY;
var p = [posX, posY];
var sample = targetLayer.sampleImage(p, [0.5, 0.5]);
var sampleAlpha = sample[3];
if( sampleAlpha < 0.2 )
{
p = findPointOnLayer(targetLayer, functionSeed+1);
}
return p;
}
var circleLayer = thisComp.layer("circle");
var seed = effect("seed")("Slider");
findPointOnLayer(circleLayer, seed);
To trouble shoot. I have tried the expression below, which will likewise check if the dot layers is postioned on top of the circle layer. If it isn't, instead of the recursive call, it will set p to [0,0]. That works.
function findPointOnLayer(targetLayer, functionSeed)
{
seedRandom(functionSeed, true);
var rndX = Math.random();
var rndY = Math.random();
var posX = thisComp.width * rndX;
var posY = thisComp.height * rndY;
var p = [posX, posY];
var sample = targetLayer.sampleImage(p, [0.5, 0.5]);
var sampleAlpha = sample[3];
if( sampleAlpha < 0.2 )
{
p = [0, 0];
}
return p;
}
var circleLayer = thisComp.layer("circle");
var seed = effect("seed")("Slider");
findPointOnLayer(circleLayer, seed);
Sample project is attached. Any help is much appreciated.
- Jakob
