Выражение if else after effects
I wrote this section many years ago and while the if/else formatting I present in the single-line examples below is not technically correct, the After Effects expression engine has always accepted it. The October 2018 release of AE includes a new, more strict JavaScript engine. While you can still get away with this:
I'd recommend that you just always use curly braces to enclose your statements, like this:
if/else Conditional Code
When writing expressions you will often encounter a situation where your code needs to make a decision based on some condition. As a simple example, say you had a rotating object where you wanted it to have 100% opacity if it was pointing to the right but only 50% opacity if it was pointing to the left. Assuming that a rotation of zero degrees corresponds to our object pointing up, we could use JavaScript's conditional "if/else" pair to implement this very easily. The code for our Opacity expression looks like this:
Let's's break this down. "if" is the JavaScript keyword that tells the expression that this is a conditional statement. Next comes (always in parentheses) the condition to test for. In our example we're checking to see if the rotation is less than 180 degrees. The next part ("100" in this case) tells the expression what to do if the condition is true. In our case "100" will be the expression-ending code that causes the opacity to be set to 100. Next comes the optional JavaScript keyword "else" that tells After Effects that we also have something that we want the statement to do if the condition is false. Finally you have the piece that tells the expression what to do if the condition is false. In our example, if the condition is false, Opacity will be set to 50 instead of 100.
There are other ways to structure this and we'll examine a few here. Notice that you can have an "if" statement without an "else" clause. We could have used this code to get the same results:
An important thing to note here is that the expression must evaluate to something or it will generate an error. For example, if you were to enter this expression:
After Effects would accept it and you might think that everything was OK, but the expression would fail as soon as the Rotation value exceeded 180 because After Effects wouldn't have anything to use as the final result. Now let's look at slightly more complicated way to set up our first example:
This version accomplishes exactly the same thing as our first example. So why would we do it in a more complicated way? Well, in this case we probably wouldn't. But it illustrates an important concept. This is how you can have the expression execute multiple statements based on the condition. The key is the curly braces (""). You can use these in either (or both) of the true and false parts of the expression. Note that there are different ways to format the curly braces, but I like the style above and that's what you'll see in the examples on this site. Using the braces you can include as many statements as you like in each section of the expression. You can even include additional if/else constructs.
Comparison and Equality Operators
This is probably a good place to mention JavaScript's comparison operators. In our first examples above we've been using the "less than" (<) operator to compare two operands in the condition part of the if statement. There are some others that you will find very useful, such as "greater than" (>), "less than or equal" (<=), and "greater than or equal" (>=). There are also a few "equality operators", two of which you will use often. These are "equality" (==), which evaluates to true if the two operands it separates are equal, and "inequality" (!=), which evaluates to true if the two operands are not equal. It is very common to make the mistake of using a single " and" (&&), logical "or" (||), and logical "not" (!). Logical "and" evaluates to true if the operands on both sides of it are true. Logical "or" evaluates to true if an operand on either side is true. Logical "not" only has one operand (immediately to its right) and it inverts the state of its operand. That is, it evaluates to true if its operand is false and evaluates to false if its operand is true.
Let's look at a couple of examples. Let's go back to our first example and change the requirements a little. Let's say that now we want Opacity to be 100 if Rotation is less than 90 or greater than 270 and 50 otherwise. Our new code will look like this:
logical operator example
This expression is saying "set Opacity to 100 if Rotation is less than 90 or greater than 270". It's important to notice the precedence of the operators. "" are evaluated before "||" so we don't need to add any additional parentheses to the expression.
OK - we'll look at one more example. Let's say that what we really want is Opacity of 100 when Rotation is between 0 and 90 or between 180 and 270, otherwise we want Opacity to be 50. Here's the code that will accomplish that:
multiple logical operators
You'll notice that we have used both the logical "or" and the logical "and" in this expression. Also note that the "&&" operation is evaluated before the "||" operation - again eliminating the need to add extra parentheses.
Продолжаю гулять по «базе». На этот раз рассмотрим конструкцию else if. Это обычная конструкция «условия»: если условие верно (истинно), то выполняется определенный блок, если нет, то выполняется другой блок. Наверняка похожие операторы условия вы проходили еще в школе, на уроках информатики, я, например, много лет назад, познавал это в QBASIC’е.
Структура кода проста:
- Condition – выражение, являющееся условием для проверки
- Блок кода 1 – блок, который выполняется, если условие верно
- Блок кода 2 – блок, который выполняется, если условие ложно
Здесь есть условие: если rotation меньше 180 градусов, то прозрачность будет равняться 100, если условие не верно, то 50 (иными словами, если rotation будет равняться больше 180 градусам)
Кроме того, мы можешь использовать эту конструкцию без «else» оператора, если в случае когда условие не верно, идет возвращение значения, например как здесь:
Здесь в случае, когда условие не верно, то есть rotation > 180, значение возвращается, мы получаем начальное t = 50
Как вы видите в синтаксисе кода, чтобы выражение работало, необязательно ставить фигурные скобки «< >» между блоками else – if. Почему же стоит писать так:
Все потому что эти фигурные скобки позволяют выполнять несколько блоков кода, с одним условием, кроме того они позволяют вставить несколько блоков условия else-if. Например:
> else if (условие)
Самой частой ошибкой новичков является либо нарушение синтаксиса, например, не заключили в скобки условие:
Текст ошибки «Expected : (.» Которая говорит о том, что ожидалась скобка, а не «ожидался грустный смайл».
Вторая ошибка у новичков, это потеря блока else если условие не верно:
Текст ошибки «Object of type Layer found where a Number, Array, or Property is needed»
Как я уже писал выше, можно обойтись без else блока, только в том случае если вы делаете «возврат» значение или переменной.
If/Else expressions are incredibly useful in After Effects…if you know how to use them.
You don’t have to be a computer programmer to get a handle on expressions in After Effects. Let’s dig into the powerful If/Else expression in After Effects.
What is an If/Else Expression in After Effects?
An If/Else expression in After Effects is a line of code that will change it’s output value based on the input value. If this sounds confusing, don’t worry! It’s simplier than you might think. Let’s take a look at a really basic model:
In this example, the code states that if the white shape’s opacity is more than 50% than the text opacity will be 100%. If the white squares opacity is less than 50% the text opacity will be 50%.
Here’s what our After Effects timeline looks like for this example:
How to Write an If/Else Conditional Expression
Writing an If/Else statement is fairly straight forward. Simply open up your expression editor by holding down Option and clicking on the stopwatch next to the parameter you want the If/Else statement to effect. The expression used in the example above is:
if(thisComp.layer(“WhiteShape”).transform.opacity>50) 100 else 50
What do each of the parameters in this expression mean? Let’s break them down step by step:
1. Declare the ‘If’ Statement
2. Define Your Input Value
Using the pickwhip tool select the value you want to input into your If/Else statement. For the example above, the input value came from the opacity of the white shape. So in that example we would pickwhip to the opacity of the white shape.
3. Set Your Equality Operator
An equality operator is essentially a small formula designed to tell your expression what to do. The following chart explains what equality operators you can use in After Effects.
For the above example we will use the greater than (>) operator.
4. Define Your Conditional Value
The conditional value can be any number you want. In our example the conditional value was 50.
5. Close the Parenthesis
Write: )
6. Add the “true” value
Type in the value you want your expression to output if your conditional statement is true. Look at the example again…if the value of the square was in fact more than 50 (true) than our output value would be 100.
7. Define the ‘Else’ Statement
An else statement will define a value if the “if” statement is false. Write: Else
8. Add the False value
The false value pertains to the value that will be output if the “if” statement isn’t true. In our example, if the opacity value of the shape was not greater than 50 (false) than the opacity of the text would be 50.
9. Close the Expression
Write: ;
How Can I Use If/Else Expressions in After Effects?
There are a number of different reasons why a motion graphic designer might want to use If/Else statements in After Effects. Here are just a few.
Value Based Conditionals
One of the most useful applications of an If/Else statement in After Effects is to have an object’s opacity directly linked to another type of value. For example, the blinking box below has an if statement that says if it’s rotation is greater than 180 than the value should be 0. If the value is less than 180 the value should be 100.
If/Else Conditionals on Checkboxes
Checkboxes are typically used when creating templates for others to use in After Effects. Typically checkboxes control opacity, but they can be used to manipulate other things like color or scale. Checkboxes work with If/Else statements by declaring two values: one if the box is selected (1) and one if the box is not selected (0) using an else statement.
Position Based If/Else Statements
One of the uses best uses that I’ve found for If statements in After Effects is linking layer opacity to an object’s position using an If/Else statement. In short, using this method you can tell certain layers to turn ‘off’ and ‘on’ depending on where an object is currently positioned.
Resources:
If you want to learn more about If/Else statements or expressions in After Effects check out a few of the following resources:
How do you use If/Else statements in After Effects? Share in the comments below.
еще один пример
Проверяешь по индексу
tryif(thisComp.layer("Controls").effect("Layer Control")("Layer"))if(thisComp.layer("Controls").effect("Layer Control")("Layer").index == thisLayer.index)else>>catch(err)
это в поле opacity
loopOut(); для повтора ключевых кадров
100*Math.sin(time*15); запишите в rotation для амплитуды анимации
wiggle(30,60); для рандомного выбора числа, где 30- количество повторов 60- на сколько изменится
time*100; для для значений по типу "rotation"
для значений по типу "position"
расширенные значения wiggle
freq = 1;
amp = 110;
loopTime = 3;
t = time % loopTime;
var wiggle1 = wiggle(freq, amp, 1, 10, t);
wiggle2 = wiggle(freq, amp, 1, 10, t - loopTime);
linear(t, 0, loopTime, wiggle1, wiggle2)
исключить ось Z
если используете партикуляр и источник света Motion Path
иногда нужно привязать партикуля к источнику света
нужно дописать к каждой привязке почти в конце .position.valueAtTime(0)
Particular Emitter Position XY:
pos = thisComp.layer("Motion Path 1").position.valueAtTime(0);
[pos[0], pos[1]]
Particular Emitter Position Z:
thisComp.layer("Motion Path 1").position.valueAtTime(0)[2]
Экспрешн, который автоматически притречивает 2Д слой к 3Д слою, лежащего в таймлайне под 2Д слоем
Применять к положению
//position
pos = thisComp.layer("1").transform.position;//[x,y];
frame = thisComp.frameDuration;
K = thisComp.layer("controller").effect("K")("Slider");
//thisComp.layer("1").transform.position.valueAtTime();
delay = K*frame*(index-1);
postNew = pos.valueAtTime(time-delay);
[value[0],postNew[1]];
//rotation
rot = thisComp.layer("1").transform.rotation;
frame = thisComp.frameDuration;
K = thisComp.layer("controller").effect("K")("Slider");
//thisComp.layer("1").transform.position.valueAtTime();
delay = K*frame*(index-1);
rotNew = rot.valueAtTime(time-delay);
// null
temp = thisComp.layer("1").transform.position.valueAtTime(0);
temp - [0,-50];
//animation cube
recPosX = thisComp.layer("rec").transform.position[0];
start = thisComp.layer("start").transform.position[0];
end = thisComp.layer("end").transform.position[0];
TRK1 = timeRemap.key(1).value;
TRK2 = timeRemap.key(2).value;
linear(recPosX,start,end,TRK1,TRK2);
ребят, предлагаю сюда скидывать различные интересные экспрешшоны и пояснения к ним) мельком пролистал 87 тем и вроде не увидел аналогичной темы. а тема интересная блин! expressions значительно упрощают задачу и ускоряют работу, делают результат гораздо динамичней и красивей. короче плюсов дофига, минусов нету)
начну пожалуй с самого популярного экспрешшона рунета, автором которого является Тимур Константинов. вот скрипт:
mp = .1;//Чем больше значение, тем больше амблитуда
freq = 5;//Чем больше значение, тем больше частота
decay = 7;//Чем больше значение, тем меньше задержка
n = 0;
if (numKeys > 0)<
n = nearestKey(time).index;
if (key(n).time > time)<
n--;
>
>
if (n == 0)<
t = 0;
>else<
t = time - key(n).time;
>
if (n > 0)<
v = velocityAtTime(key(n).time - thisComp.frameDuration/10);
value + v*amp*Math.sin(freq*t*2*Math.PI)/Math.exp(decay*t);
>else<
value;
>
точнее - вот так:
amp = .1;
freq = 5;
decay = 7;
n = 0;
if (numKeys > 0)n = nearestKey(time).index;
if (key(n).time > time)n--;
>
>
if (n == 0)t = 0;
>elset = time - key(n).time;
>
if (n > 0)v = velocityAtTime(key(n).time - thisComp.frameDuration/10);
value + v*amp*Math.sin(freq*t*2*Math.PI)/Math.exp(decay*t);
>elsevalue;
>
да, спасибо. скопипастил криво) можно и с комментариями оставить после amp/frec/decay, потому что за двойным слешем программа не читает скрипт и туда можно вписывать пометки и комментарии
вот ссылка на несколько полезных выражений
вот те,которыми я пользуюсь:
Для оси X:
Math.cos(S*time)*360
Для оси Y:
Math.sin(S*time)*360
Для колес эволюции и оси Z:
time*S
amp = 15; //amplitude (pixels)
freq = 10; //frequency (cycles per second)
n = 0;
if (numKeys > 0)<
n = nearestKey(time).index;
if (key(n).time > time)<
n--;
>
>
if (n == 0)<
t = 0;
>else<
t = time - key(n).time;
>
if (n > 0)<
v = velocityAtTime(key(n).time - thisComp.frameDuration/10);
amp = .05;
freq = 4.0;
decay = 2.0;
value + v*amp*Math.sin(freq*t*2*Math.PI)/Math.exp(decay*t);
>else<
value;
>
,где amp - амплитуда, freq - частота, а decay - затухание
Серега маслов, это вообще не Тимура скрипт)) А Хэрри Фрэнка с грэй машин)
Но экспрешн реально полезный)
2 Владислав Соловьев
а по моему - это просто код программирования.
зная язык, можно самому написать без Генри и Тимура
Владислав Соловьев
спасибо за разъяснение, буду знать) спасибо тем, кто поддержал тему! продолжаемв том же духе))
Вовка, это то да)
Просто этот экспрешн я видел давным давно еще на старой версии сайта грэй машин) А вообще Хэрри Фрэнк очень неплохо рассказывает, советы дельные)
origin = [10,10,10];//описываем стандартный размер массива (таблица)
dimX = 10;//к-во ячеек по X
dimY = 10;//к-во ячеек по Y
dimZ = 10;//к-во ячеек по Z
gap = 50;//максимально расстояние между ячейками
gridRate = 500;//скорость движения частиц
holdTime = .1;//максимальная задержка по времени
//описываем необходимые переменные, заранее обнулив их
start = 0;
startX = 0;
startY = 0;
startZ = 0;
endX = 0;
endY = 0;
endZ = 0;
deltaX = 0;
deltaY = 0
deltaZ = 0;
end = 0;
j = 0;//переменная, необходимая для проведения цикла и дальнейшей проверки значений
while (time >= end) //цикл, аналог цикла "for"
seedRandom(j,true); //генератор случайных чисел
//задаем начальные позиции элемента
startX = Math.floor(random(dimX))*gap + origin[0]; //по X
startY = Math.floor(random(dimY))*gap + origin[1]; //по Y
startZ = Math.floor(random(dimZ))*gap + origin[2]; //по Z
j +=1;//наращиваем значение j на единичку с каждым шагом, т.е. в следующем цикле
произойдет новое перемещение объекта
seedRandom(j,true) //снова рандомим
start = end; //присваиваем значению "end" значение "start" для просчета
конечной позиции элемента
//========«строчим все как для старрта»==========
endX = Math.floor(random(dimX))*gap + origin[0];
endY = Math.floor(random(dimY))*gap + origin[1];
endZ = Math.floor(random(dimZ))*gap + origin[2];
deltaX = Math.abs(endX - startX);
deltaY = Math.abs(endY - startY);
deltaZ = Math.abs(endZ - startZ);
//теперь конечная позиция будет менятся в каждом новом цикле
end += (deltaX + deltaY + deltaZ)/gridRate + 3*holdTime;
>
p1 = start + deltaX/gridRate; //определено рандомное расположение объекта и первое движение по X
p2 = p1 + holdTime; //второе движение c задержкой
p3 = p2 + deltaY/gridRate;//третье со смещением по Y
p4 = p3 + holdTime;// четвертое с задержкой
p5 = p4 + deltaZ/gridRate; //пятое со смещением по Z
//========«проверка на порядок действий (порядок движения) и движение по-этапное»=========
if (time < p1)
ease(time,start,p1,[startX,startY,startZ],[endX,startY,startZ]) //изменение позиции с мягким ключом (короче в виде часиков песочных :D)
>
else if (time < p2)
[endX,startY,startZ] //первое смещение
>
else if (time < p3)
ease(time,p2,p3,[endX,startY,startZ],[endX,endY,startZ]) //третье движение
>
else
if (time < p4)
[endX,endY,startZ] //четвертое
>
else
if (time < p5)
ease(time,p4,p5,[endX,endY,startZ],[endX,endY,endZ]) //пятое
>
else
[endX,endY,endZ]
>
//движение элемента теперь будет происходить рандомно по сетке по направлениям X,Y и Z
Читайте также: