Using Animation Curves

All keyframes added to an Animation Property of a node in an Animation Clip are shown as linear traces in the corresponding animation property track, which is an animation curve. That is, an Animation Curve describes the change in an Animation Property on an object over time.

The Animation Curve stores internally a series of time points, each of which corresponds to a (curve) value, called a frame (keyframe). When the animation system runs, the Animation Component calculates the (result) value that should be assigned to the object at the specified time point based on the current animation state and completes the property change, a calculation process called sampling.

The following code snippet demonstrates how to create Animation Clips programmatically:

  1. import { AnimationClip, animation, js } from 'cc';
  2. const animationClip = new AnimationClip();
  3. animationClip.duration = 1.0; // The entire period of the animation clip, the frame time of any keyframe should not be greater than this property
  4. animationClip.keys = [ [ 0.3, 0.6, 0.9 ] ]; // The frame time shared by all curves of the clip
  5. animationClip.curves = [{ // Animation curves on the Animation component
  6. modifiers: [ // Address the target object from the current node object. See the "Target Objects" section below for details
  7. // The target object is the "Body" child of the current node.
  8. HierarchyPath('Body'),
  9. // The target object is the "MyComponent" component on the "Body" child of the current node.
  10. ComponentPath(js.getClassName(MyComponent)),
  11. // The target object is the "value" property on the "MyComponent" component of the "Body" child of the current node.
  12. 'value',
  13. ],
  14. data: {
  15. // Indexed to 'animationClip.keys', i.e. [ 0.3, 0.6, 0.9 ]
  16. keys: 0,
  17. // Keyframe data
  18. values: [ 0.0, 0.5, 1.0 ],
  19. },
  20. }];

The above Animation Clip contains an Animation Curve that controls the value property of the MyComponent component in the Body child node. The Animation Curve includes three keyframes that make the value property change to 0.0 at 0.3 seconds, 0.5 at 0.6 seconds, and 1.0 at 0.9 seconds.

Note: the frame times of the keyframes on the animation curve are indexed by reference to the AnimationClip.keys array. In this way, multiple curves can share frame times, which will result in additional performance optimization.

Target objects (modifiers)

The target of an animation curve can be any JavaScript object. The modifiers field specifies how the target object is addressed from the current node object at runtime.

modifiers is an array, each element of which expresses how to address an object from a higher level to another object, with the last element addressed as the target of the curve. This behavior is like a file system path, so each element is called a “target path”.

When the target path is string or number, it addresses the property of the higher-level object, which itself specifies the property name. Otherwise, the target path must be an object that implements the interface animation.TargetPath.

Cocos Creator has the following built-in classes that implement the interface animation.TargetPath:

  • animation.HierarchyPath treats a higher-level object as a node and addresses one of its children
  • animation.ComponentPath treats a higher-level object as a node and addresses one of its components

The target paths can be any combination, as long as they have the correct meaning:

  1. modifiers: [
  2. // The target object is the first element of the "names" property of the "BlahBlahComponent" component on the "nested_3" child node of the "nested_2" child node of the "nested_1" child node
  3. new animation.HierarchyPath('nested_1/nested_2/nested_3'),
  4. new animation.ComponentPath(js.getClassName(BlahBlahComponent)),
  5. 'names',
  6. 0,
  7. ]

Custom target paths are useful when the target object is not an property, but must be returned from a method:

  1. class BlahBlahComponent extends Component {
  2. public getName(index: number) { return _names[index]; }
  3. private _names: string[] = [];
  4. }
  5. modifiers: [
  6. // The target object is the first "name" of the "BlahBlahComponent" component on the "nested_3" child node of the "nested_2" child node of the "nested_1" child node
  7. new animation.HierarchyPath('nested_1/nested_2/nested_3'),
  8. new animation.ComponentPath(js.getClassName(BlahBlahComponent)),
  9. {
  10. get: (target: BlahBlahComponent) => target.getName(0),
  11. },
  12. ]

For custom target paths to be serializable, declare them as classes:

  1. @ccclass
  2. class MyPath implements animation.TargetPath {
  3. @property
  4. public index = 0;
  5. constructor(index: number) { this.index = index; }
  6. get (target: BlahBlahComponent) {
  7. return target.getName(this.index);
  8. }
  9. }
  10. modifiers: [
  11. // The target object is the first "name" of the "BlahBlahComponent" component on the "nested_3" child node of the "nested_2" child node of the "nested_1" child node
  12. new animation.HierarchyPath('nested_1/nested_2/nested_3'),
  13. new animation.ComponentPath(js.getClassName(BlahBlahComponent)),
  14. new MyPath(0),
  15. ]

The addressing of the target object is done at runtime, a feature that allows animation clips to be reused on multiple objects.

Assignment

When a value is sampled, by default the value will be set to the target object using the assignment operator =.

Sometimes, the assignment operator cannot be used to complete the setting. For example, when setting the Uniform of a material object, it can’t be done with the assignment operator. For this case, the curve field valueAdapter provides a mechanism to customize the value to the target object.

Example:

  1. class BlahBlahComponent {
  2. public setUniform(index: number, value: number) { /* */ }
  3. }
  4. { // Curve
  5. valueAdapter: {
  6. // Called when the curve is instantiated
  7. forTarget(target: BlahBlahComponent) {
  8. // Do something useful here
  9. return {
  10. // Called each time the value of the target object is set
  11. set(value: number) {
  12. target.setUniform(0, value);
  13. }
  14. };
  15. }
  16. },
  17. };

For the custom assignment to be serializable, declare them as classes:

  1. @ccclass
  2. class MyValueProxy implements animation.
  3. @property
  4. public index: number = 0;
  5. constructor(index: number) { this.index = index; }
  6. // Called when the curve is instantiated
  7. public forTarget(target: BlahBlahComponent) {
  8. // Do something useful here
  9. return {
  10. // Called each time the value of the target object is set
  11. set(value: number) {
  12. target.setUniform(0, value);
  13. }
  14. };
  15. }
  16. }

UniformProxyFactory is one such custom assignment class that implements setting the uniform value of a material:

  1. {
  2. modifiers: [
  3. // The target object is the first material of the "sharedMaterials" property of the "MeshRenderer" component
  4. ComponentPath(js.getClassName(MeshRenderer)),
  5. 'sharedMaterials',
  6. 0,
  7. ],
  8. valueAdapter: new animation.UniformProxyFactory(
  9. 0, // Pass index
  10. 'albedo', // Uniform name
  11. ),
  12. };

Sampling

If the sampled time point is exactly equal to the time point of a keyframe, then the animation data on that keyframe is used. Otherwise, when the sampling time point is between two frames, the result value is affected by the data of both frames, and the scale of the sampling time point on the moment interval of the two keyframes ([0, 1]) reflects the extent of the effect.

Cocos Creator allows this scale to be mapped to another scale to achieve a different “fade” effect. These mapping methods are called fading methods in Creator. After the scale is determined, the final result is calculated based on the specified interpolation method.

Note: both the fade method and the interpolation method affect the smoothness of the animation.

Fade method

The fade method for each frame can be specified, or a uniform fade method can be used for all frames. The fade method can be the name of a built-in fade method or a Bessel control point.

The following are some of the commonly used fade methods:

  • linear: maintains the original scale, i.e. linear gradient, which is used by default when no gradient is specified
  • constant: always use scale 0, i.e. no gradient, similar to interpolation Step.
  • quadIn: fade from slow to fast
  • quadOut: fade from fast to slow
  • quadInOut: fading from slow to fast to slow again
  • quadOutIn: fade from fast to slow to fast

Expand Comparison

Curve values and interpolation methods

Some interpolation algorithms require additional data to be stored in the curve value for each frame, so the curve value is not necessarily the same as the value type of the target property. For numeric types or value types, Cocos Creator provides several general interpolation methods. Also, it is possible to define custom interpolation methods.

  • When the interpolate property of the curve data is true, the curve will try to use the interpolation function.

    • If the curve value is of type number, Number, linear interpolation will be applied.
    • If the curve value inherits from ValueType, the lerp function of ValueType will be called to complete the interpolation. lerp methods for most value types built into Cocos Creator are implemented as linear interpolation, e.g.: Vec3, vec4, etc.
    • If the curve value is interpolable, the lerp function for the curve value will be called to complete the interpolation1.
  • If the curve value does not satisfy any of the above conditions, or when the interpolate property of the curve data is false, no interpolation will be performed and the curve value from the previous frame will always be used as the result.

    1. import { AnimationClip, color, IPropertyCurveData, SpriteFrame, Vec3 } from 'cc';
    2. const animationClip = new AnimationClip();
    3. const keys = [ 0, 0.5, 1.0, 2.0 ];
    4. animationClip.duration = keys.length === 0 ? 0 : keys[keys.length - 1];
    5. animationClip.keys = [ keys ]; // All curves share one column of frame time
    6. // Linear interpolation using values
    7. const numberCurve: IPropertyCurveData = {
    8. keys: 0,
    9. values: [ 0, 1, 2, 3 ],
    10. /* interpolate: true, */ // "interpolate" property is on by default
    11. };
    12. // Using lerp() of value type Vec3
    13. const vec3Curve: IPropertyCurveData = {
    14. keys: 0,
    15. values: [ new Vec3(0), new Vec3(2), new Vec3(4), new Vec3(6) ],
    16. interpolate: true,
    17. };
    18. // No interpolation (because interpolation is explicitly disabled)
    19. const colorCuve: IPropertyCurveData = {
    20. keys: 0,
    21. values: [ color(255), color(128), color(61), color(0) ],
    22. interpolate: false, // No interpolation
    23. };
    24. // No interpolation (because SpriteFrame cannot be interpolated)
    25. const spriteCurve: IPropertyCurveData = {
    26. keys: 0,
    27. values: [
    28. new SpriteFrame(),
    29. new SpriteFrame(),
    30. new SpriteFrame(),
    31. new SpriteFrame()
    32. ],
    33. };
  • Custom interpolation algorithm

    The sample code is as follows:

    1. import { ILerpable, IPropertyCurveData, Quat, quat, Vec3, vmath } from 'cc';
    2. class MyCurveValue implements ILerpable {
    3. public position: Vec3;
    4. public rotation: Quat;
    5. constructor(position: Vec3, rotation: Quat) {
    6. this.position = position;
    7. this.rotation = rotation;
    8. }
    9. /** This method will be called for interpolation
    10. * @param this initial curve value
    11. * @param to target curve value
    12. * @param t interpolation ratio, in the range [0, 1]
    13. * @param dt the frame time interval between the starting curve value and the target curve value
    14. */
    15. lerp (to: MyCurveValue, t: number, dt: number) {
    16. return new MyCurveValue(
    17. // The position property is not interpolated
    18. this.position.clone(),
    19. // The rotation property uses Quat's lerp() method
    20. this.rotation.lerp(to.rotation, t), //
    21. );
    22. }
    23. /** This method is called when not interpolating
    24. * It is optional, if this method is not defined, then the curve value itself (i.e. this) is used as the result value
    25. */
    26. getNoLerp () {
    27. return this;
    28. }
    29. }
    30. /**
    31. * Creates a curve that implements a smooth rotation but abrupt position change throughout the cycle.
    32. */
    33. function createMyCurve (): IPropertyCurveData {
    34. const rotation1 = quat();
    35. const rotation2 = quat();
    36. const rotation3 = quat();
    37. vmath.quat.rotateY(rotation1, rotation1, 0);
    38. vmath.quat.rotateY(rotation2, rotation2, Math.PI);
    39. vmath.quat.rotateY(rotation3, rotation3, 0);
    40. return {
    41. keys: 0 /* frame time */,
    42. values: [
    43. new MyCurveValue(new Vec3(0), rotation1),
    44. new MyCurveValue(new Vec3(10), rotation2),
    45. new MyCurveValue(new Vec3(0), rotation3),
    46. ],
    47. };
    48. }

Wrap mode

Different wrap modes can be set for Animation Clips by setting AnimationClip.wrapMode. The following lists several common wrap modes:

PropertyDescription
NormalPlayback stops at the end
WrapMode.LoopLoop
PingPongPlay from the beginning to the end of the animation, then play back to the beginning from the end, and so on.

For more wrap modes, please refer to the WrapMode API and the Wrap Mode and Repeat Count documentation.

  1. For numeric, quaternion, and various vectors, Cocos Creator provides the appropriate interpolate classes to implement Cubic Spline Interpolation.