Skip to main content
Inspiring
November 7, 2021
Answered

Get time of the previous and next keyframe

  • November 7, 2021
  • 1 reply
  • 1665 views

Hi need guidance.

What should be the logic of the script so that from the time of the current key, I could get the time of the previous and next keyframe.

Regards

This topic has been closed for replies.
Correct answer Paul Tuersley

 


You always need to take care to understand what you're looping through and deal with the correct range.

Generally speaking, if you're accessing something with square brackets [x] it will be a 0 based index, while if you're acessing it using round brackets (x) it will be a 1 based index.

The difference being myArray[x] is an 'array' of values and arrays always start from 0, while keyTime(x) is a 'method' and in AE scripting an index for a method (layers, keyframes, etc) will generally start from 1.

 

If you have say 3 values in an array you'd loop with something like:

for (x = 0; x < myArray.length; x++) {

while with 3 items in a 1 based index it would be:

for (x = 1; x <= myProp.numItems; x++) {

 

Notice the <= in the second loop. In the first you loop from 0 to 2 (less than length of 3) while in the second it's from 1-3 (less than or equal to 3)

 

Here's something that covers the full range:

var theProp = app.project.activeItem.selectedProperties[0];

if (theProp.numKeys == 0) alert("no keyframes");
else if (theProp.numKeys == 1) alert("only one key at " + theProp.keyTime(1));
else {

	for (var x = 1; x <= theProp.numKeys; x++) {
		
		if (x == 1) { // first loop, there will be no previous key but there must be a next key as we know there are more than one to be here
			alert("loop " + x + " current= " + theProp.keyTime(x) + " next = " + theProp.keyTime(x+1));
		} else if (x == theProp.numKeys) { // last loop. there will be no next key
			alert("loop " + x + " last= " + theProp.keyTime(x-1) + " current = " + theProp.keyTime(x));
		} else { // there must be both previous and next keys
			alert("loop " + x + " last= " + theProp.keyTime(x-1) + " current = " + theProp.keyTime(x) + " next= " + theProp.keyTime(x+1));
		}

	}
}

1 reply

Inspiring
November 7, 2021
var theProp = app.project.activeItem.selectedProperties[0];

var nearestKeyIndex = theProp.nearestKeyIndex(app.project.activeItem.time);

alert("nearest key index = " + nearestKeyIndex + " time = " + theProp.keyTime(nearestKeyIndex));

if (nearestKeyIndex > 1) alert("last key index = " + (nearestKeyIndex-1) + " time = " + theProp.keyTime(nearestKeyIndex-1));
if (nearestKeyIndex < theProp.numKeys) alert("next key index = " + (nearestKeyIndex+1) + " time = " + theProp.keyTime(nearestKeyIndex+1));

 

https://ae-scripting.docsforadobe.dev/properties/property.html#property-nearestkeyindex

 

HarchenkoAuthor
Inspiring
November 8, 2021

Thanks Paul