Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Activity Forums Adobe After Effects Expressions script to swap the positions of n layers?

  • script to swap the positions of n layers?

    Posted by Juanluis Vich on June 24, 2022 at 10:28 pm

    hello!

    I have a small issue with a need, but I don’t quite know which of these two options would be more efficient.

    I have a series of layers (which may vary and which are actually comps) . Each one is in a fixed position. I need that with each execution of a script, the layers change between their positions, randomly and without repetitions.

    As possibility A, a script that makes random swap between positions given a number n of layers.

    As possibility B, to randomly replace each layer by selecting the layers and at the same time the compositions in the bin, making a multiple and random replacement on each script execution

    Exploring the possibilities of option A, I have found this script https://gist.github.com/ff6347/3468163 that works perfectly between 2 layers, but I don’t know how to adapt it to work on a selection of layers.
    That script says:

     var layers = app.project.activeItem.selectedLayers;

    var pos1, pos2;
    
    
    for (var i = 0; i < 2; i++){
    	if(i ==0) pos1 = layers[i].position.value;
    	if(i ==1) pos2 = layers[i].position.value;
    
    	// layers[i].position.selected = true;
    
    
    };
    
    layers[0].position.setValue(pos2);
    layers[1].position.setValue(pos1);

    If anyone can shed some light I would greatly appreciate it.
    Surely if I had done it by hand I would have finished by now and in less time invested than doing fruitless tests, but anything to learn something new!

    Juanluis Vich replied 1 year, 2 months ago 2 Members · 2 Replies
  • 2 Replies
  • Dan Ebberts

    June 25, 2022 at 2:56 am

    This is a simple example that will take the selected layers and randomly swap their positions. Might give you some ideas, or a place to start:

    var myLayers = app.project.activeItem.selectedLayers;

    var myPositions = [];

    for (var i = 0; i < myLayers.length; i++){

    myPositions.push(myLayers[i].property("Position").value);

    }

    var temp;

    var idx;

    for (var i = 0; i < myPositions.length; i++){

    idx = i + Math.floor(generateRandomNumber()*(myPositions.length-i));

    temp = myPositions[i];

    myPositions[i] = myPositions[idx];

    myPositions[idx] = temp;

    }

    for (var i = 0; i < myLayers.length; i++){

    myLayers[i].property("Position").setValue(myPositions[i]);

    }

  • Juanluis Vich

    June 25, 2022 at 3:11 am

    this!!! thank you very much!! it’s awesome!

We use anonymous cookies to give you the best experience we can.
Our Privacy policy | GDPR Policy