Skip to main content
Participant
July 15, 2025
Question

After Effect expression for text visibility and position control

  • July 15, 2025
  • 0 replies
  • 111 views

Hi,

I'm a beginner to After Effect expressions. I'm creating a end creadit MOGRT for my team. There are total 16 text layers, named as "Title", "Name", Title 1" "Name 1" etc. and controled by 8 checkboxes, named as "Group 1", "Group 2" etc. two layers per checkbox. The vertical gap between "Title" layers and "Name"  layers should be 15 pixels, and 40 between groups. If one of the groups is unchecked the visible groups will move up. All the stacked visible groups should be vertically centred in the comp.

 

I tested with 6 layers. Except to keep the gap remain as I asked for after adding multiple lines in "Name" layer, everything works well with the expression generated by Chatgpt.  I would be super grateful if someone could let me know which part has gone wrong in the below expression script, and how to fix it. The image on the left is the fulty result and on the right is what I would like to acheive.

      

// Fixed x position

x = 785;

 

// Layer order (must match actual layer names)

layerNames = [

  "TItle", "Name",

  "Title 2", "Name 2",

  "Title 3", "Name 3"

];

 

// Corresponding gaps before each layer (15 or 40)

gaps = [0, 15, 40, 15, 40, 15];

 

// Group visibility flags (2 layers per group)

ctrl = thisComp.layer("Controls");

groupsVisible = [];

for (i = 1; i <= 3; i++) {

  groupsVisible.push(ctrl.effect("Group " + i)("Checkbox") == 1);

}

 

// Determine visibility per layer (true/false)

visible = [];

for (i = 0; i < 3; i++) {

  if (groupsVisible[i]) {

    visible.push(true);  // Title

    visible.push(true);  // Name

  } else {

    visible.push(false);

    visible.push(false);

  }

}

 

// Get layer index in layout

myIndex = layerNames.indexOf(name);

 

// Helper: get height of layer

getHeight = function(layerName) {

  return thisComp.layer(layerName).sourceRectAtTime(time, false).height;

};

 

// Compute total block height

totalHeight = 0;

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

  if (visible[i]) {

    totalHeight += getHeight(layerNames[i]);

    if (i > 0 && gaps[i] > 0) totalHeight += gaps[i];

  }

}

 

// Starting Y (top of first visible layer)

startY = thisComp.height / 2 - totalHeight / 2;

 

// Stack up visible layers above current one

y = startY;

for (i = 0; i < myIndex; i++) {

  if (visible[i]) {

    y += getHeight(layerNames[i]);

    if (gaps[i + 1] !== undefined) y += gaps[i + 1];

  }

}

 

// Add half height of current layer to align center

if (visible[myIndex]) {

  y += getHeight(layerNames[myIndex]) / 2;

  [x, y];

} else {

  // Move offscreen if invisible

  [x, -2000];

}