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

nearestKeyIndex()

Community Beginner ,
Mar 26, 2024 Mar 26, 2024

Copy link to clipboard

Copied

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

Views

92

Translate

Translate

Report

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
Enthusiast ,
Mar 26, 2024 Mar 26, 2024

Copy link to clipboard

Copied

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);

 

Votes

Translate

Translate

Report

Report
Community Beginner ,
Mar 27, 2024 Mar 27, 2024

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report