search
HomeWeb Front-endJS TutorialAfter Effects: The Modulo Operator (%)

In-depth explanation of the modulo operator (%) in After Effects expressions

The modulo operator (%), also known as the remainder operator, is a very useful tool in expression construction, but it may not be easy for beginners to understand. This article explains its functionality and uses.

% is used to calculate the remainder of an equation. For example:

<code>10 % 3</code>

This expression returns 1 because the quotient of 10 divided by 3 is 3, the remainder is 1.

This is useful for creating loops when working with time variables.

Loop expression

Most designers new to After Effects expressions are familiar with the loopOut() expression. It allows us to use "cycle" (cycle from start to end), "pingpong" (cycle from start to end and back to the start), "offset" (repeat keyframes but each time with a offset of value to build the animation) or "continue" (to continue the motion using the speed of the last keyframe) to cycle through keyframe properties. This is very comprehensive and covers everything you need for keyframe animation.

However, if you want to loop an expression, loopOut is not a viable solution. There may be many reasons for not wanting to use keyframes, but the main one is if a value needs to be updated dynamically, and constantly. It's much easier to update an expression attached to a slider than it is to update a set of keyframes.

If the motion is continuous, then Linear or Ease will suffice. But for complex animations that require looping, we can use the time modulo operator to implement the loop.

To see how this works, copy and paste the following expression into the text layer’s Source Text property:

<code>Math.floor(time % 5)</code>

You will see the layer count from 0 to 4 every second, looping back to 0 every 5 seconds. This is because the remainder of the expression changes every second as time passes:

随时间变化的余数
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
The Math.floor function rounds the argument to an integer.

After Effects: The Modulo Operator (%)

From this, it's easy to see how to use it when you need to animate numbers between specific parameters.

Example: Digital Clock

Let’s use % to make a digital clock.

The seconds need to count between 0 and 60, and the minutes need to be incremented every 60 intervals. Let’s paste this into the text layer’s Source Text property again:

<code>10 % 3</code>

Breaking up the expression, our sec variable will count from 0 to 60, and the minute variable will be incremented on every multiple of 60 (again, we use Math.floor to round the numbers). The if statement that follows adds a 0 in front of the sec variable if it is less than 10, ensuring that our seconds variable always has two digits (you can repeat this for the minutes as well, if you want). Then just use time separators to combine them together.

After Effects: The Modulo Operator (%)

If you need the counter to work independently of time, you can achieve the same effect by replacing the time with a slider and setting its value.

You can also make the time separator blink using the modulo operator and the After Effects text expression selector.

Go to the text layer and add the Opacity animation option to the text layer (if you’re not sure how to do this, you can check out all about this in this article). Then add expression selector and remove range selector.

After Effects: The Modulo Operator (%)

Set the opacity in the animator to 0 and add this expression to the Amount property:

//Digital clock separator flashes //Add to expression selector

minute = Math.floor(time / 60);

minute = 10 && textIndex == 3 ? Math.floor(time2 % 1.5) 100 : 0;

I wrote a conditional statement based on the fact that the number of digits in the minutes variable is not fixed. First, I copy the minutes variable from the source text property. I then use this to calculate the textIndex value of the time separator. When there is only one digit in the minute display, it will equal 2. When the minutes display exceeds 10, it will be 3. Conditional statements can also be written as if statements, as shown below, to further explain what it is doing:

if (minute = 10 && textIndex == 3) Math.floor(time2 % 1.5) 100 else 0

If minutes is less than 10 and textIndex is equal to 2, then Math.floor(time2 % 1.5) 100 affects the second character in the text layer. This will make the letters flash (on/off ratio 2:1) thanks to the modulo operator. The Math.floor function rounds the number, and the entire expression is finally multiplied by 100 to toggle between 0 and 100, which is the range of the expression selector.

However, if minutes is equal to or greater than 10 and textIndex is equal to 3, the effect will be applied to the third character in the text layer. This explains the extra digits in the minute display. If your minutes display needs to be longer than 99, you will need to add another parameter to affect the display of the time separator when it is in the fourth position.

However, if your minute display is set to a constant number of digits, this statement becomes much simpler:

dividerIndex = 3; textIndex == dividerIndex ? Math.floor(time2 % 1.5) 100 : 0

After Effects: The Modulo Operator (%)

That’s it, you get a digital clock!

After showing how the modulo operator helps create loops, we can now consider how it can be applied to other properties.

Example: Analog Clock

Now let’s make an analog clock. When the pointer ticks, it's usually not a continuous movement but one that stops and starts suddenly. This is the type of loop that the modulo operator can help solve.

Let’s take a look at the following expression that can be pasted into the rotation property of the clock hands layer:

//Second hand rotates frames = thisComp.frameDuration;

loopTime = 1; dur = frames * 6; strength = 6;

counter = Math.floor(time/loopTime); t = time % loopTime;

ease(t, 0, dur, strength counter, strength (counter 1))

First, we set some variables. frames is the duration of a frame in the composition, allowing it to work across multiple frame rates.

Set loopTime to the time you want to loop. I want the loop to last one second, so I set it to 1. dur is the duration of the animation within the loop, so I set it to frames * 6, making it last 6 frames. strength is the change in animation value, since I'm animating the clock hands I set it to 6 so the clock hands will complete one rotation in 60 ticks.

Next, I create a counter variable that will help offset my value. I created it using Math.floor(time/loopTime) , using Math.floor to round the numbers and setting the speed of the counter to match the loop. Finally, t is a variable we can use to time expression-driven animations. This is time % loopTime, so when time reaches the number stored in loopTime, time loops.

After that, we can animate. In this example, I use the ease expression. By setting the first parameter to t, we remap the rotation value to our loop time variable. The next two parameters are 0 and dur, the start and end points of the animation. The last two parameters are strength counter and strength (counter 1), which is the value of the rotation property. By multiplying strength by counter, we can offset the value of each loop, ending at strength * (counter 1), ready for the next loop.

After Effects: The Modulo Operator (%)

The advantage of driving motion via expressions rather than keyframes in this case is if you need to build a clock template for changing times. The static value of the expression can be connected to the slider, making it easier to update continuously.

You can use more advanced expressions or build your own functions to create more customized animations:

//Second hand rotates frames = thisComp.frameDuration;

loopTime = 1; dur = frames * 6; change = 6;

counter = Math.floor(time/loopTime); t = time % loopTime;

function easeInOutBack (t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) (tt(((s=(1.525))) 1)t - s )) b; return c/2((t-=2)t(((s=(1.525)) 1)t s) 2) b; }

easeInOutBack(t, 0, change, dur, 1.70158)

After Effects: The Modulo Operator (%)

Finally, you can create a variable to set the starting value and use an if statement to skip the first iteration of the minute hand (and possibly hour hand) animation:

//Minute hand rotation frames = thisComp.frameDuration;

loopTime = 60; dur = frames * 6; strength = 6; startValue = 180;

counter = Math.floor(time/loopTime); t = time % loopTime;

function easeInOutBack (t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) (tt(((s=(1.525))) 1)t - s )) b; return c/2((t-=2)t(((s=(1.525)) 1)t s) 2) b; }

if (counter > 0) { easeInOutBack(t, startValue strength * counter, strength, dur, 1.70158) } else { startValue }

After Effects: The Modulo Operator (%)

From here, just connect the slider to our startValue variable. This way you have an analog clock that can be updated by simply changing the value in the slider.

Conclusion

The modulo operator is useful for creating loops to aid in dynamic expressions where other methods are not suitable for the needs of the project.

Try testing it in your own project!

Any comments? Is there anything unclear? Please leave a comment below.

The above is the detailed content of After Effects: The Modulo Operator (%). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor