Skip to main content
Participating Frequently
March 26, 2024

nearestKeyIndex()

  • March 26, 2024
  • 2 replies
  • 300 views

When the layer time is reversed, NearestKeyIndex() behaves unexpectedly. It always returns 1, which messes up all calculations. I've searched online for a solution, but it seems this problem has been discussed for over 10 years. Do you have any plans to address this issue or add more functionality for working with keyframes? Alternatively, a suggested workaround would be greatly appreciated to help me complete my project.

2 replies

MotionApeAuthor
Participating Frequently
March 27, 2024

@Airweb_AEThanks, this function suits my needs. But when the layer is flipped, still several calculations go wrong. Fixing them one by one is too hard; we need permanent solutions involving the keyframe object.

Legend
March 26, 2024

Maybe using a custom nearestKeyIndex function:

function nearestKeyIndex(prop, time, reversed) {
  var keyTimes = [];
  var keyCount = prop.numKeys;
  for (var i = 1; i <= keyCount; i++) {
    keyTimes.push(prop.keyTime(i));
  }
  if (keyTimes.length === 0) {
    return null;
  }
  if (reversed) {
    keyTimes.reverse()
  }
  var nearestIndex = 0;
  var nearestDiff = Math.abs(time - keyTimes[nearestIndex]);
  for (var j = 1; j < keyTimes.length; j++) {
    var diff = Math.abs(time - keyTimes[j]);
    if (diff < nearestDiff) {
      nearestDiff = diff;
      nearestIndex = j;
    }
  }
  return nearestIndex + 1;
}
var proj = app.project;
var thisComp = proj.activeItem;
var timeToCheck = thisComp.time;
var nearestKey = nearestKeyIndex(thisComp.layer(1).transform.position, timeToCheck, true);