Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
1

nearestKeyIndex()

Community Beginner ,
Mar 26, 2024 Mar 26, 2024

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.

Bug Unresolved
TOPICS
Scripting
216
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
2 Comments
Advocate ,
Mar 26, 2024 Mar 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);

 

Translate
Report
Community Beginner ,
Mar 27, 2024 Mar 27, 2024
LATEST

@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.

Translate
Report